You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib中为坐标轴添加字号不同的次要标签?

Solution for Adding Subplot Letter Labels (A, B, C...) in Matplotlib

Got it, let's tackle this problem! You're already set up with your 3x3 subplot grid, and now you want to add those letter labels (A, B, C, etc.) in specific positions with a smaller font size than your main axis labels. Here's a straightforward, flexible approach:

Step-by-Step Implementation

  1. Use ax.text() with relative coordinates: The key here is to use transform=ax.transAxes—this lets you position text relative to the subplot itself (instead of data coordinates), so the labels stay in the right spot even if you adjust the plot size.
  2. Loop through your subplots: Pair each subplot with a corresponding letter label, then place the text where you need it (most commonly the top-left corner, but you can adjust the coordinates for your target position).
  3. Set distinct font sizes: Specify a smaller fontsize for the letter labels compared to your main axis labels.

Full Code Example

import matplotlib.pyplot as plt

# Your existing subplot setup
fig, axs = plt.subplots(3, 3, sharex=True, sharey=True, constrained_layout=False)

# Define your letter labels (match the number of subplots)
labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

# Loop through each subplot and add the label
for ax, label in zip(axs.flat, labels):
    # Position the label at the top-left of the subplot (adjust coordinates as needed)
    # (0.05, 0.95) = 5% from left, 95% from bottom of the subplot
    ax.text(0.05, 0.95, label, 
            transform=ax.transAxes,  # Use subplot-relative coordinates
            fontsize=8,  # Smaller than main axis labels
            fontweight='bold',  # Optional: make labels stand out
            va='top')  # Align text to the top of the y-coordinate

# Add your main axis labels (your existing method)
fig.supxlabel('X-axis label here', fontsize=12)
fig.supylabel('Y-axis label here', fontsize=12)

# Adjust layout if needed (fixes overlapping)
plt.tight_layout()

plt.show()

Customization Tips

  • Adjust label position: If your target position isn't the top-left, tweak the x and y values in ax.text(). For example:
    • Top-right: (0.95, 0.95) with ha='right'
    • Bottom-left: (0.05, 0.05) with va='bottom'
  • Font styling: Modify fontweight, color, or fontfamily to match your target graph's style.
  • Avoid overlap: If labels clash with axes or ticks, adjust the coordinate values (e.g., use 0.1 instead of 0.05 for more space from the left edge) or enable constrained_layout=True in your subplots() call.

内容的提问来源于stack exchange,提问作者Mahmoud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 15:52:33