How to Add Text Inside the Plot in Matplotlib
We use the matplotlib.pyplot.text()
method to add text inside a plot in Matplotlib.
matplotlib.pyplot.text()
Method
matplotlib.pyplot.text()
adds text to the figure or to the axes in Matplotlib.
Syntax
matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
x
and y
represent the coordinates where we need to place the text, and s
is the text’s content that needs to be added. The fontdict
parameter is a dictionary used to set the properties of the text.
Examples: Add Text Inside the Plot Matplotlib Using matplotlib.pyplot.text()
Method
import matplotlib.pyplot as plt
plt.text(0.55, 0.55, "Hello World!", fontsize=20, color="green")
plt.show()
Output:
It will simply put the text inside the plot at position (0.55, 0.55)
with font size as 20
and green
color. By default, the limit of both the X-axis and Y-axis ranges from 0 to 1, so we won’t be able to see the text out of this range.
To put the text at any position with the X-axis or Y-axis out of the range (0,1)
, we need to change the limit of the respective axis.
import matplotlib.pyplot as plt
plt.text(4, 6, "Hello World!", fontsize=20, color="green")
plt.xlim([0, 10])
plt.ylim([0, 10])
plt.show()
Output:
We can also add various styling to the text using the **kwargs
.
import matplotlib.pyplot as plt
plt.text(
5,
5,
"Hello World!",
fontsize=20,
color="red",
verticalalignment="top",
horizontalalignment="center",
bbox={"facecolor": "grey", "pad": 10},
)
plt.xlim([0, 10])
plt.ylim([0, 10])
plt.show()
Output:
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn