How to Add Text to Plot in Matplotlib: Simple Guide
Use the
plt.text(x, y, 'text') function to add text at coordinates (x, y) on a Matplotlib plot. You can customize the text style and position with optional parameters.Syntax
The basic syntax to add text to a plot is plt.text(x, y, 'text', **kwargs), where:
xandyare the coordinates where the text will appear.'text'is the string you want to display.**kwargsare optional styling parameters likefontsize,color, androtation.
python
plt.text(x, y, 'Your text here', fontsize=12, color='blue', rotation=0)
Example
This example shows how to plot a simple line and add text at a specific point on the plot.
python
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] plt.plot(x, y, marker='o') plt.text(3, 5, 'Point (3,5)', fontsize=12, color='red') plt.title('Example of Adding Text to Plot') plt.xlabel('X axis') plt.ylabel('Y axis') plt.show()
Output
A line plot with points marked and the text 'Point (3,5)' displayed near the point (3,5) in red color.
Common Pitfalls
Common mistakes when adding text to plots include:
- Placing text outside the visible plot area by using wrong coordinates.
- Not calling
plt.show()to display the plot. - Using coordinates that do not match the data scale (e.g., using data coordinates when axes are logarithmic).
Always check your coordinate system and plot limits.
python
import matplotlib.pyplot as plt # Wrong: text outside plot plt.plot([1, 2, 3], [4, 5, 6]) plt.text(10, 10, 'Outside plot') # This text won't be visible plt.show() # Right: text inside plot plt.plot([1, 2, 3], [4, 5, 6]) plt.text(2, 5, 'Inside plot') plt.show()
Output
First plot shows no visible text because coordinates (10,10) are outside the plot range; second plot shows text 'Inside plot' near point (2,5).
Quick Reference
| Function | Description | Example |
|---|---|---|
| plt.text(x, y, s) | Add text at data coordinates (x,y) | plt.text(1, 2, 'Hello') |
| plt.xlabel('label') | Set label for x-axis | plt.xlabel('Time') |
| plt.ylabel('label') | Set label for y-axis | plt.ylabel('Value') |
| plt.title('title') | Set plot title | plt.title('My Plot') |
| plt.annotate() | Add text with arrow annotation | plt.annotate('Max', xy=(3,5), xytext=(4,6), arrowprops=dict()) |
Key Takeaways
Use plt.text(x, y, 'text') to add text at specific plot coordinates.
Customize text appearance with optional parameters like fontsize and color.
Ensure text coordinates are within the plot limits to make text visible.
Call plt.show() to display the plot with added text.
Use plt.annotate() for advanced text with arrows and positioning.