Home » Tutorial on Matplotlib Annotations in Python

Tutorial on Matplotlib Annotations in Python

Spring Framework Basics Video Course
Oracle Java Certification
Java SE 11 Programmer II [1Z0-816] Practice Tests
1 Year Subscription
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]

Annotations in Matplotlib are powerful tools that allow you to add context, explanations, or any additional information directly on your plots.

They help in making plots more informative and are highly customizable to fit a wide range of needs.

In this tutorial, we’ll go over the basics of annotations in Matplotlib, along with code examples for different types of annotations you might find useful.

1. Basic Annotation

The basic syntax for adding annotations in Matplotlib is with the annotate function, which has the following form:

plt.annotate('Text', xy=(x, y), xytext=(x_text, y_text), arrowprops=dict())
  • Text: The annotation text.
  • xy: The point (x, y) where the annotation should point to.
  • xytext: The location (x_text, y_text) where the text should be placed.
  • arrowprops: Properties of the arrow (optional).

Here’s a simple example:

import matplotlib.pyplot as plt

# Create some data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]

# Plot the data
plt.plot(x, y, marker='o')

# Annotate a specific point
plt.annotate('Important Point', xy=(3, 25), xytext=(4, 30),
             arrowprops=dict(facecolor='black', arrowstyle='->'))

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Basic Annotation Example")
plt.show()

2. Adding Multiple Annotations with Different Arrow Styles

You can customize the arrow style to better indicate certain points on your plot. Matplotlib offers several arrow styles, such as ->, -[, |-|, etc.

# Create another plot
plt.plot(x, y, marker='o')

# Add multiple annotations with different arrow styles
plt.annotate('Arrow A', xy=(2, 20), xytext=(1, 30),
             arrowprops=dict(facecolor='blue', arrowstyle='->'))
plt.annotate('Arrow B', xy=(4, 30), xytext=(3, 15),
             arrowprops=dict(facecolor='red', arrowstyle='-[', linestyle='--'))

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Annotations with Different Arrow Styles")
plt.show()

3. Styling Text in Annotations

Matplotlib also lets you style the text in your annotations. You can change the font size, color, and add background colors to make the text stand out.

# Add annotations with styled text
plt.plot(x, y, marker='o')

plt.annotate('Bold & Red', xy=(2, 20), xytext=(1, 25),
             color='red', fontsize=12, fontweight='bold',
             arrowprops=dict(facecolor='black', arrowstyle='->'))
plt.annotate('Green & Italics', xy=(4, 30), xytext=(3, 10),
             color='green', fontsize=10, fontstyle='italic',
             arrowprops=dict(facecolor='black', arrowstyle='->'))

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Styled Text in Annotations")
plt.show()

4. Using bbox to Customize Annotation Box Background

To make the annotation text stand out, you can add a background box (bbox) around it, and this can be styled with different colors, edge styles, and padding.

# Plot with bbox styling
plt.plot(x, y, marker='o')

plt.annotate('Highlighted Box', xy=(3, 25), xytext=(4, 20),
             bbox=dict(boxstyle="round,pad=0.3", edgecolor="black", facecolor="yellow"),
             arrowprops=dict(facecolor='black', arrowstyle='->'))

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Annotation with bbox")
plt.show()

5. Adding Annotations with Coordinate Transformations

You can use transform to place annotations in a specific location on the figure (like fixed at the top or bottom) rather than at a data-specific point.

# Set up the plot
plt.plot(x, y, marker='o')

# Use transform to place annotation in figure coordinates
plt.annotate('Top Center', xy=(0.5, 0.95), xycoords='figure fraction', ha='center', fontsize=12)

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Annotation with Coordinate Transformation")
plt.show()

6. Complex Annotations: Arrow Properties, Background Colors, and Alignment

For more complex annotations, you can adjust the arrow properties, text alignment, and add customized background.

# Set up the plot
plt.plot(x, y, marker='o')

# Add complex annotation
plt.annotate(
    'Complex Annotation',
    xy=(3, 25), xytext=(2, 35),
    arrowprops=dict(facecolor='purple', edgecolor='grey', arrowstyle='fancy', connectionstyle='arc3,rad=.5'),
    bbox=dict(boxstyle="round,pad=0.5", edgecolor="grey", facecolor="lightblue"),
    ha='center'
)

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Complex Annotation Example")
plt.show()

7. Annotating Multiple Points with a Loop

If you want to annotate multiple points with the same style, you can use a loop for more efficiency.

# Sample data
points = [(1, 10), (2, 20), (3, 25), (4, 30), (5, 35)]

# Plot the data points
plt.plot(x, y, marker='o')

# Annotate each point
for point in points:
    plt.annotate(f'{point}', xy=point, xytext=(point[0]+0.2, point[1]+3),
                 arrowprops=dict(facecolor='black', arrowstyle='->'))

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Annotating Multiple Points")
plt.show()

Summary

In this tutorial, we've explored various ways to add annotations to Matplotlib plots, including:

  • Basic annotations with text and arrows.
  • Different arrow styles.
  • Styling text in annotations.
  • Adding background colors using bbox.
  • Placing annotations in figure coordinates.
  • Using loops to annotate multiple points.

By customizing annotations, you can make your visualizations more effective and help your audience quickly understand the key points in your data!

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More