Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Annotate Subplots in a Figure with A, B, C using Matplotlib
To annotate subplots in a figure with A, B, and C using Matplotlib, you can add text labels to each subplot using the text() method with appropriate positioning coordinates.
Steps to Annotate Subplots
- Set the figure size and adjust the padding between and around the subplots
- Create a figure and a set of subplots with nrows=1 and ncols=3
- Make a 1D iterator over the axes array using
flat - Iterate through each axes and display data as an image
- Use
text()method to place letters A, B, and C on each subplot - Display the figure using show() method
Example
Here's how to create three subplots with A, B, C annotations ?
import numpy as np
import matplotlib.pyplot as plt
import string
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, axs = plt.subplots(1, 3)
axs = axs.flat
for index, ax in enumerate(axs):
ax.imshow(np.random.randn(4, 4), interpolation='nearest', cmap="copper")
ax.text(0.45, 1.1, string.ascii_uppercase[index],
transform=ax.transAxes,
size=20, weight='bold')
plt.show()
Key Parameters
The text() method uses several important parameters ?
- Position (0.45, 1.1): x=0.45 centers horizontally, y=1.1 places above the subplot
- transform=ax.transAxes: Uses axes coordinates (0-1 range) instead of data coordinates
- string.ascii_uppercase[index]: Gets letters A, B, C automatically
- size=20, weight='bold': Makes the annotation prominent and readable
Alternative Positioning
You can position annotations in different locations ?
import numpy as np
import matplotlib.pyplot as plt
import string
fig, axs = plt.subplots(1, 3, figsize=(10, 4))
positions = [(0.05, 0.95), (0.05, 0.05), (0.95, 0.95)] # Top-left, bottom-left, top-right
for index, ax in enumerate(axs):
ax.imshow(np.random.randn(4, 4), interpolation='nearest', cmap="viridis")
x, y = positions[index]
ax.text(x, y, string.ascii_uppercase[index],
transform=ax.transAxes,
size=16, weight='bold',
bbox=dict(boxstyle="round,pad=0.3", facecolor="white", alpha=0.8))
plt.tight_layout()
plt.show()
Output
Conclusion
Use ax.text() with transform=ax.transAxes for consistent positioning across subplots. The string.ascii_uppercase module provides an easy way to automatically generate sequential letters for annotation.
Advertisements
