Matplotlib Text: Customize Plots with Labels & Annotations
Master Matplotlib text features for powerful data visualization. Add titles, labels, annotations, math, and Unicode for insightful AI/ML plots.
Working with Text in Matplotlib
Matplotlib offers robust support for creating and customizing text within plots, enabling a high degree of flexibility. You can enhance your visualizations with titles, labels, annotations, mathematical expressions, Unicode characters, and even dynamic text animations. Matplotlib also embeds fonts directly into documents to ensure consistent rendering across different platforms and outputs.
Text Functions in Matplotlib
Matplotlib provides both implicit and explicit interfaces for handling text.
Implicit API
These functions are typically called on the pyplot
module or directly on an Axes
object.
text(x, y, s)
: Adds texts
at the specified coordinates(x, y)
.annotate(text, xy, xytext)
: Creates annotations, often including arrows to point to specific locations.xlabel(xlabel)
: Sets the label for the x-axis.ylabel(ylabel)
: Sets the label for the y-axis.title(title)
: Adds a title to the current subplot (Axes).figtext(x, y, s)
: Places texts
at the specified figure coordinates(x, y)
.suptitle(t)
: Adds a title to the entire figure, typically above all subplots.
Explicit API
These methods are called directly on an Axes
object, providing a more object-oriented approach.
set_xlabel(xlabel)
: Sets the label for the x-axis of the Axes.set_ylabel(ylabel)
: Sets the label for the y-axis of the Axes.set_title(title)
: Adds a title to the Axes.text(x, y, s)
: Adds texts
at the specified coordinates(x, y)
within the Axes.figure.suptitle(t)
: Adds a title to the entire figure (wherefigure
is aFigure
object).
Each of these functions returns a Text
instance, which can be further customized with various font properties and styles.
1. Adding Titles to Figures and Subplots
Titles can be added at two main levels:
- Figure Level: Use
fig.suptitle()
to add a title that spans the entire figure. - Subplot Level: Use
ax.set_title()
(orplt.title()
) to add a title to an individual subplot (Axes).
Example: Adding Titles
import matplotlib.pyplot as plt
import numpy as np
# Generate data
x_values = np.linspace(0.0, 5.0, 100)
y_values = np.cos(2 * np.pi * x_values) * np.exp(-x_values)
# Create a plot with a figure and an axes
fig, ax = plt.subplots(figsize=(7, 4))
fig.subplots_adjust(bottom=0.15, left=0.2) # Adjust layout for better visibility
ax.plot(x_values, y_values)
# Add a figure-level title
fig.suptitle('Figure Suptitle', fontsize=14, fontweight='bold')
# Add an axes-level title
ax.set_title('Axes Title')
# Display the plot
plt.show()
2. Adding Labels to Axes
Axis labels are essential for understanding what each axis represents. You can add them using:
ax.set_xlabel()
andax.set_ylabel()
(Explicit API)plt.xlabel()
andplt.ylabel()
(Implicit API)
Example: Adding Axis Labels
import matplotlib.pyplot as plt
import numpy as np
# Generate data
x_values = np.linspace(0.0, 5.0, 100)
y_values = np.cos(2 * np.pi * x_values) * np.exp(-x_values)
# Create a plot
fig, ax = plt.subplots(figsize=(7, 4))
fig.subplots_adjust(bottom=0.15, left=0.2)
ax.plot(x_values, y_values)
# Add axis labels
ax.set_xlabel('X-Axis Label')
ax.set_ylabel('Y-Axis Label')
# Display the plot
plt.show()
3. Adding Mathematical Expressions and Unicode Text
Matplotlib seamlessly integrates with LaTeX-like syntax for rendering mathematical expressions and also supports displaying Unicode characters. The ax.text()
function is commonly used for this purpose.
Example: Mathematical Expressions and Unicode Text
import matplotlib.pyplot as plt
# Create a subplot
fig, ax = plt.subplots(figsize=(7, 4))
fig.subplots_adjust(top=0.85) # Adjust layout to make space for suptitle
# Set figure title
fig.suptitle('Exploring Mathematical Expressions and Unicode Text')
# Set axis limits for better text placement
ax.axis([0, 10, 0, 10])
# Add a mathematical expression using LaTeX syntax
ax.text(1.5, 7, r"Einstein's energy-mass equivalence equation: $E=mc^2$",
bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10},
style='italic',
fontsize=12)
# Add Unicode text
ax.text(3, 5, 'Unicode: \u03c0 (pi), \u2211 (sum)', color='green', fontsize=15)
# Display the plot
plt.show()
Note: The r
before the string in r"Einstein's..."
indicates a raw string, which is useful for LaTeX expressions to avoid issues with backslashes.
4. Creating Animated Text
Matplotlib's animation module (matplotlib.animation
) allows for dynamic updates to text properties over time, creating engaging visualizations.
Example: Animated Text
from matplotlib import animation
import matplotlib.pyplot as plt
# Set figure size and layout for better presentation
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create figure and axes
fig = plt.figure()
ax = fig.add_subplot(111)
# Initial text
initial_text = 'Matplotlib Animation!'
txt = ax.text(0.5, 0.5, initial_text, fontsize=20, ha='center', va='center')
# Define colors for animation
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
# Define animation function
def animate(frame):
# Update font size based on frame number
txt.set_fontsize(frame * 1.5 + 15)
# Cycle through colors
txt.set_color(colors[frame % len(colors)])
# Optionally change text content
txt.set_text(f"Frame: {frame}")
return txt,
# Create animation
# frames=10 specifies the number of frames in the animation
# interval=200 sets the delay between frames in milliseconds
anim = animation.FuncAnimation(fig, animate, frames=10, interval=200, blit=True)
# Display animation
plt.show()
5. Customizing Text Properties
You have extensive control over the appearance of text elements. Key properties include:
fontsize
: Controls the size of the text.fontweight
: Sets the boldness of the text (e.g.,'normal'
,'bold'
).color
: Defines the text color.style
: Specifies the font style (e.g.,'normal'
,'italic'
,'oblique'
).bbox
: A dictionary to define a bounding box around the text, allowing customization offacecolor
,alpha
(transparency), andpad
(padding).rotation
: Rotates the text by a specified angle (in degrees).ha
: Horizontal alignment ('center'
,'right'
,'left'
).va
: Vertical alignment ('center'
,'top'
,'bottom'
,'baseline'
).
Example: Customizing Text Properties
import matplotlib.pyplot as plt
# Create a plot
fig, ax = plt.subplots(figsize=(7, 4))
# Add customized text with various properties
ax.text(0.5, 0.5, 'Custom Text Example',
fontsize=16,
fontweight='bold',
color='darkblue',
style='italic',
bbox={'facecolor': 'lightblue', 'alpha': 0.7, 'pad': 12, 'edgecolor': 'blue'},
rotation=15,
ha='center',
va='center')
# Hide axes for a cleaner look
ax.axis('off')
# Display the plot
plt.show()
Conclusion
Matplotlib provides a comprehensive toolkit for managing text within plots. By leveraging its various functions and customization options, you can effectively communicate information, highlight key data points, and create visually appealing and informative graphics.
Matplotlib Text Properties: Customize Your Plots
Master Matplotlib text properties for stunning visualizations. Learn to control font, color, size, alignment, and more to enhance your data science plots.
Matplotlib Annotated Cursor: Interactive Data Insight
Enhance your Matplotlib plots with an annotated cursor. Dynamically track cursor position and display contextual data for deeper interactive data exploration and insight. Ideal for ML/AI visualizations.