0
0
MatplotlibHow-ToBeginner ยท 3 min read

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:

  • x and y are the coordinates where the text will appear.
  • 'text' is the string you want to display.
  • **kwargs are optional styling parameters like fontsize, color, and rotation.
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

FunctionDescriptionExample
plt.text(x, y, s)Add text at data coordinates (x,y)plt.text(1, 2, 'Hello')
plt.xlabel('label')Set label for x-axisplt.xlabel('Time')
plt.ylabel('label')Set label for y-axisplt.ylabel('Value')
plt.title('title')Set plot titleplt.title('My Plot')
plt.annotate()Add text with arrow annotationplt.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.