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

Matplotlib子图标注异常:所有标注集中于最后一个子图求助

解决Matplotlib子图标注全部重叠在最后一个子图的问题

你的问题核心在于使用plt.annotate()而非对应子图对象的annotate()方法。plt.annotate()默认会把标注添加到当前"活跃"的子图上,循环过程中每次绘制完子图,活跃子图会自动切换为最后一个,最终导致所有标注都叠加到最下方的子图里。

修改后的完整代码

df_cols = ['WC_015', 'WC_030', 'WC_046', 'WC_061', 'WC_076', 'WC_091', 'WC_107', 'WC_122', 'WC_137', 'WC_152', 'WC_168', 'WC_183', 'WC_213', 'WC_244', 'WC_274', 'WC_305', 'WC_366', 'WC_427', 'WC_488', 'WC_518']
fig, axs = plt.subplots(20, 1, figsize=(50,30))  #, sharex=True, sharey=True)

for k, col in enumerate(df_cols):
    df[col].plot(ax=axs[k])
    # 关键修改:调用当前子图对象的annotate方法
    axs[k].annotate(df_cols[k], xy=(.01, .115), xycoords='axes fraction', fontsize=15, rotation=90, color='red')

fig.subplots_adjust(hspace=0)
plt.suptitle('Volumetric Moisture Content', fontsize=40, y=.91)

# 优化坐标轴标签:避免仅最后一个子图有y轴标签
for ax in axs:
    ax.set_ylabel('Volumetric Moisture Content (m3/m3)', fontsize=30)
# 仅给最后一个子图设置x轴标签(如果开启sharex=True更合理)
axs[-1].set_xlabel('Date', fontsize=30)

plt.savefig('Moisture_Content_Plots.pdf', dpi=100, bbox_inches='tight')

核心修改说明

  • 替换plt.annotate()为axs[k].annotate(),确保标注被精准添加到当前循环对应的子图上
  • 原代码中plt.ylabel()只会给最后一个子图添加y轴标签,通过循环给每个子图设置标签,或者使用fig.text()添加全局y轴标签更符合布局逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 06:15:05