Add Text Inside the Plot in Matplotlib
The matplotlib.pyplot.text() function is used to add text inside the plot. The syntax adds text at an arbitrary location of the axes. It also supports mathematical expressions.
Examples of Adding Text Inside the Plot
1. Adding Mathematical Equations
In this example, we plot a parabola (y = x²) and add text inside the plot.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-10, 10, 0.01)
y = x**2
# Adding text inside the plot
plt.text(-5, 60, 'Parabola $Y = x^2$', fontsize=22)
plt.plot(x, y, c='g')
plt.xlabel("X-axis", fontsize=15)
plt.ylabel("Y-axis", fontsize=15)
plt.show()
Output:

Explanation: np.arange(-10, 10, 0.01) creates x-values, y = x**2 forms the parabola, text Parabola Y=x2 is added at (-5, 60) and the green curve is plotted with axis labels.
2. Adding a Rectangular Box Around Text
We can also place text inside a colored box using the bbox parameter.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-10, 10, 0.01)
y = x**2
plt.xlabel("X-axis", fontsize=15)
plt.ylabel("Y-axis", fontsize=15)
# Adding text inside a rectangular box
plt.text(-5, 60, 'Parabola $Y = x^2$', fontsize=22,
bbox=dict(facecolor='red', alpha=0.5))
plt.plot(x, y, c='g')
plt.show()
Output:

Explanation: The parabola y=x2 is plotted in green and text Parabola Y=x2 is added at (-5, 60) inside a semi-transparent red box using bbox.
3. Adding Simple Labels ("Sine wave")
We can add descriptive labels like âSine waveâ at any point in the plot.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.plot(x, y)
# Adding text inside the plot
plt.text(3.5, 0.9, 'Sine wave', fontsize=23)
plt.xlabel('X-axis', fontsize=15)
plt.ylabel('Y-axis', fontsize=15)
# plt.grid(True, which='both') # Uncomment to show grid
plt.show()
Output:

Explanation: np.arange(0, 10, 0.1) generates x-values, y = np.sin(x) creates the sine wave, text Sine wave is added at (3.5, 0.9) and the curve is displayed with axis labels.
4. Adding Text with Annotation (Arrows)
Annotations are useful when you want to point to a specific part of a plot.
import matplotlib.pyplot as plt
x = ['Rani', 'Meena', 'Raju', 'Jhansi', 'Ram']
y = [5, 7, 9, 2, 6]
plt.bar(x, y)
# Adding text inside the plot
plt.text(3, 7, 'Student Marks', fontsize=18, color='g')
plt.xlabel('Students', fontsize=15)
plt.ylabel('Marks', fontsize=15)
# Annotating the highest score
plt.annotate('Highest scored', xy=(2.4, 8),
xytext=(3, 9), fontsize=16, color='g',
arrowprops=dict(facecolor='red'))
plt.show()
Output:

Explanation: A bar chart of student marks is plotted, text Student Marks is added at (3, 7) and plt.annotate() highlights the highest score (Raju) with a green label and red arrow.