Skip to content

Matplotlib - Working With Text

Matplotlib offers comprehensive text support, enabling you to add labels, titles, annotations, and mathematical expressions to your plots. It handles various fonts, unicode characters, and text layouts.

You have fine-grained control over text properties like font size, weight, color, rotation, alignment, and position. Matplotlib also includes a powerful engine for rendering mathematical expressions using a subset of TeX markup.

Common Text Functions (Object-Oriented API)

Section titled “Common Text Functions (Object-Oriented API)”

When using the recommended object-oriented approach, you typically call text-related methods on Axes or Figure objects:

MethodDescription
ax.set_title()Set the title for the Axes.
ax.set_xlabel()Set the label for the Axes’ x-axis.
ax.set_ylabel()Set the label for the Axes’ y-axis.
ax.text()Add text at an arbitrary location within the Axes coordinates.
ax.annotate()Add an annotation (text and optionally an arrow) at a specific point in the Axes.
fig.suptitle()Add a centered title to the entire Figure.
fig.text()Add text at an arbitrary location within the Figure coordinates.

All these functions return a matplotlib.text.Text object, which allows for further customization after creation.

This script demonstrates using various text functions with the object-oriented API:

import matplotlib.pyplot as plt
import numpy as np
# Prepare data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create Figure and Axes
fig, ax = plt.subplots(figsize=(8, 6))
# Plot data
ax.plot(x, y, label='sin(x)')
# --- Add Text Elements ---
# Titles and Labels
ax.set_title('Plot with Various Text Elements', fontsize=16)
ax.set_xlabel('X-axis values', fontsize=12)
ax.set_ylabel('Y-axis values', fontsize=12)
# Simple text using data coordinates
ax.text(1, 0.8, 'Simple text at (1, 0.8)', fontsize=10)
# Text with background box and style
ax.text(3, -0.5, 'Styled Text', style='italic', fontsize=12,
bbox={'facecolor': 'lightblue', 'alpha': 0.5, 'pad': 5})
# Mathematical expression (using TeX)
ax.text(6, 0.5, r'Equation: $E = mc^2$', fontsize=14, color='green')
# Text using axes coordinates (0,0 is bottom-left, 1,1 is top-right)
ax.text(0.05, 0.95, 'Top-left corner (Axes Coords)',
transform=ax.transAxes, # Specify coordinate system
verticalalignment='top', fontsize=10)
# Annotation pointing to a specific data point
point_x = x[50]
point_y = y[50]
ax.plot(point_x, point_y, 'ro') # Mark the point
ax.annotate('Annotation Here', xy=(point_x, point_y), xytext=(point_x + 1, point_y + 0.3),
arrowprops=dict(facecolor='black', shrink=0.05, width=1, headwidth=8))
# --- Final Touches ---
ax.legend()
ax.grid(True, linestyle='--', alpha=0.6)
ax.axis([0, 10, -1.2, 1.2]) # Set axis limits slightly wider
plt.tight_layout() # Adjust layout
plt.show()

This code will generate a plot showing a sine wave with various text elements: a main title, axis labels, text placed using data coordinates, styled text with a background box, a mathematical equation rendered using TeX, text positioned relative to the axes boundaries, and an annotation pointing to a specific data point with an arrow.

  • Data Coordinates: By default, ax.text() uses the same coordinate system as your plotted data.
  • Axes Coordinates: Use transform=ax.transAxes for placement relative to the Axes bounding box (0,0 is bottom-left, 1,1 is top-right). Useful for text in fixed locations like corners.
  • Figure Coordinates: Use transform=fig.transFigure for placement relative to the entire Figure canvas.
  • Annotations: ax.annotate() is powerful for labeling specific features, automatically handling text and arrow placement based on xy (point to annotate) and xytext (text position).