0
0
Matplotlibdata~5 mins

Text boxes with bbox in Matplotlib

Choose your learning style9 modes available
Introduction

Text boxes with bounding boxes help highlight or separate text in a plot. They make important information stand out clearly.

You want to label a specific point on a graph with a highlighted note.
You need to add a title or comment inside a plot area with a colored background.
You want to explain a part of a chart with a box around the text for clarity.
You want to create a legend or annotation with a border and background color.
Syntax
Matplotlib
plt.text(x, y, 'Your text', bbox=dict(boxstyle='round', facecolor='color', alpha=opacity))

x and y set the position of the text on the plot.

The bbox argument defines the style and color of the box around the text.

Examples
Shows text 'Hello' at center with a rounded yellow box that is semi-transparent.
Matplotlib
plt.text(0.5, 0.5, 'Hello', bbox=dict(boxstyle='round', facecolor='yellow', alpha=0.5))
Displays 'Note' with a square light blue box behind it.
Matplotlib
plt.text(0.2, 0.8, 'Note', bbox=dict(boxstyle='square', facecolor='lightblue'))
Text 'Warning' with a rounded box that has padding and a red background.
Matplotlib
plt.text(0.7, 0.3, 'Warning', bbox=dict(boxstyle='round,pad=0.3', facecolor='red', alpha=0.7))
Sample Program

This code creates a simple line plot with three points. Each point has a text label with a colored box behind it to highlight the label.

Matplotlib
import matplotlib.pyplot as plt

plt.figure(figsize=(5, 4))
plt.plot([1, 2, 3], [4, 5, 6], marker='o')

plt.text(1, 4, 'Start', bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.5))
plt.text(2, 5, 'Middle', bbox=dict(boxstyle='round,pad=0.5', facecolor='lightblue', alpha=0.7))
plt.text(3, 6, 'End', bbox=dict(boxstyle='square', facecolor='pink', alpha=0.6))

plt.title('Plot with Text Boxes')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.grid(True)
plt.show()
OutputSuccess
Important Notes

You can change boxstyle to shapes like 'round', 'square', or add padding with 'round,pad=0.5'.

The alpha controls transparency: 0 is invisible, 1 is fully solid.

Use facecolor to set the box color and edgecolor to set the border color if needed.

Summary

Text boxes with bbox highlight text on plots with colored backgrounds and borders.

Use plt.text() with the bbox argument to add these boxes.

Customize box shape, color, padding, and transparency to make your plot clear and attractive.