Add a Text Box to a Plot in Matplotlib

Recently, while working on a data visualization project in Python, I needed to highlight key insights directly on a Matplotlib chart. The challenge was to add a text box that looked clean, readable, and informative, without cluttering the plot.

I’ve been using Python for over a decade, and Matplotlib remains one of my favorite libraries for visual storytelling.

In this article, I’ll show you how to add a text box to a plot in Matplotlib using different methods that I personally use in my projects.

What Is a Text Box in Matplotlib?

A text box in Matplotlib is a rectangular area that contains text inside your chart. It’s often used to annotate or explain specific sections of your visualization.

In Python’s Matplotlib, you can add a text box using the plt.text() or ax.text() function, combined with the bbox parameter. This makes your text stand out with a background color, border, and padding.

Why Use Text Boxes in Python Matplotlib Plots?

Here are a few practical cases where I often use text boxes:

  • To highlight important data points or trends.
  • To display statistical results like mean, median, or correlation.
  • To show annotations or explanations for better readability.
  • To create professional-looking charts for presentations or reports.

Now, let’s go through the different methods you can use to add text boxes in Matplotlib.

Method 1 – Add a Simple Text Box Using plt.text() in Python

This is the simpler way to add a text box. You can use the built-in plt.text() function and pass the bbox argument to style the box.

Here’s how I do it in my projects:

import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create plot
plt.plot(x, y, label='Sine Wave', color='blue')

# Add a text box
plt.text(2, 0.8, 'Peak Point', 
         fontsize=12, 
         color='black',
         bbox=dict(facecolor='lightyellow', alpha=0.7, edgecolor='gray'))

# Add labels and title
plt.title('Adding a Text Box in Matplotlib (Python Example)')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()

# Show plot
plt.show()

You can see the output in the screenshot below.

Add a Text Box to a Plot in Matplotlib

In this example, I added a text box labeled “Peak Point” near the top of the sine wave. The bbox dictionary controls the color, transparency, and border of the box.

Method 2 – Add a Text Box Using Axes Coordinates

Sometimes, you might want the text box to stay fixed relative to the axes, not the data points. This is helpful when you want to display general information like a note or title.

Here’s how you can do it in Python:

import matplotlib.pyplot as plt
import numpy as np

# Data
x = np.linspace(0, 20, 200)
y = np.cos(x)

fig, ax = plt.subplots()
ax.plot(x, y, color='green')

# Add text box using axes coordinates
ax.text(0.05, 0.95, 
        'Note: Cosine Function', 
        transform=ax.transAxes,
        fontsize=12,
        verticalalignment='top',
        bbox=dict(facecolor='lightblue', alpha=0.5, boxstyle='round'))

ax.set_title('Add Text Box Using Axes Coordinates in Matplotlib (Python)')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

plt.show()

You can see the output in the screenshot below.

Add Text Box to a Plot in Matplotlib

In this method, I used transform=ax.transAxes to position the text box relative to the axes. It ensures that the box doesn’t move when you zoom or resize the plot.

Method 3 – Add Multiple Text Boxes for Annotations

When analyzing multiple data points, I often add more than one text box. This helps highlight specific values or sections clearly.

Here’s a practical Python example:

import matplotlib.pyplot as plt
import numpy as np

# Generate data
x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots()
ax.plot(x, y, color='purple')

# Add multiple text boxes
ax.text(1.5, 0.9, 'High Point', 
        fontsize=10, 
        bbox=dict(facecolor='orange', alpha=0.5, boxstyle='round,pad=0.5'))

ax.text(7.5, -0.8, 'Low Point', 
        fontsize=10, 
        bbox=dict(facecolor='lightgreen', alpha=0.5, boxstyle='square,pad=0.3'))

ax.set_title('Add Multiple Text Boxes in Matplotlib (Python Example)')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

plt.show()

You can see the output in the screenshot below.

Add a Text Box to a Plot Matplotlib

This approach is great when you want to label peaks, troughs, or any special event within your data. You can use different colors and box styles to make each annotation unique.

Method 4 – Add a Text Box with Dynamic Data in Python

In real-world data analysis, I often use text boxes to display dynamic values like averages or statistical results. Here’s how you can calculate and display such values directly in a Matplotlib plot.

import matplotlib.pyplot as plt
import numpy as np

# Generate random data
np.random.seed(42)
data = np.random.normal(100, 15, 200)

mean_value = np.mean(data)
std_dev = np.std(data)

# Create histogram
plt.hist(data, bins=20, color='skyblue', edgecolor='black')

# Add dynamic text box
plt.text(0.65, 0.85, 
         f'Mean: {mean_value:.2f}\nStd Dev: {std_dev:.2f}', 
         transform=plt.gca().transAxes,
         fontsize=12,
         bbox=dict(facecolor='white', edgecolor='gray', alpha=0.7))

plt.title('Add Dynamic Text Box in Matplotlib (Python Example)')
plt.xlabel('Value')
plt.ylabel('Frequency')

plt.show()

You can see the output in the screenshot below.

Text Box to a Plot in Matplotlib

This method is extremely useful for data analysis dashboards or reports. It allows you to display key metrics directly on the visualization.

Method 5 – Add Styled Text Boxes with Custom Fonts and Borders

You can also customize your text box with advanced styling options in Python. This makes your visualization more professional and presentation-ready.

import matplotlib.pyplot as plt
import numpy as np

# Data
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

fig, ax = plt.subplots()
ax.plot(x, y, color='darkred')

# Add styled text box
ax.text(np.pi/2, 0.8, 
        'Maximum Amplitude', 
        fontsize=14, 
        color='white',
        fontweight='bold',
        bbox=dict(facecolor='darkblue', edgecolor='white', boxstyle='round4,pad=0.6'))

ax.set_title('Styled Text Box in Matplotlib (Python Example)')
ax.set_xlabel('Radians')
ax.set_ylabel('Amplitude')

plt.show()

This method gives you full control over the appearance of your text box. You can modify the font size, color, weight, and even use custom box shapes like round4 or larrow.

Tips for Positioning Text Boxes in Python Matplotlib

Here are a few professional tips I’ve learned over the years:

  • Use transform=ax.transAxes when you want the text box to stay fixed in one place.
  • Use data coordinates when the box should move with the data points.
  • Experiment with verticalalignment and horizontalalignment to align text properly.
  • Keep the text short and concise for better readability.
  • Use contrasting colors for the text and background for accessibility.

Common Box Styles You Can Use

Matplotlib supports several box styles through the boxstyle parameter.
Here are some of my favorites:

Box StyleDescription
'round'Rounded corners
'square'Sharp corners
'round4'Smooth rounded edges
'larrow'Left arrow shape
'rarrow'Right arrow shape
'darrow'Double arrow shape

You can experiment with different styles depending on your design preference. These small touches can make your Python visualizations look much more polished.

Real-World Example: Annotating Sales Data in Python

Let’s take a practical U.S.-based example, annotating a sales trend for a retail company. We’ll highlight the month with the highest sales using a text box.

import matplotlib.pyplot as plt
import numpy as np

# Monthly sales data (in USD thousands)
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
sales = [120, 135, 150, 165, 210, 250, 275, 260, 230, 200, 180, 160]

max_sales = max(sales)
max_month = months[sales.index(max_sales)]

plt.plot(months, sales, marker='o', color='teal')
plt.title('Monthly Sales Trend (Python Matplotlib Example)')
plt.xlabel('Month')
plt.ylabel('Sales (in $1000s)')

# Add text box for peak month
plt.text(5.5, 260, 
         f'Peak Month: {max_month}\nSales: ${max_sales}K', 
         fontsize=11,
         bbox=dict(facecolor='lightgreen', alpha=0.6, edgecolor='darkgreen'))

plt.show()

This example shows how to use a text box to highlight key business insights directly on your chart. It’s a great way to make your Python data visualizations more informative and presentation-ready.

Adding a text box to a plot in Matplotlib is one of those small yet powerful touches that can transform your Python visualizations. It helps you communicate insights clearly, annotate key points, and make your charts look professional.

In this tutorial, I showed you different methods, from basic to advanced, to add text boxes using Python. You can now apply these techniques to your own data projects, whether for analysis, reporting, or storytelling.

I hope you found this article helpful.

You may also like to read:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.