You need to enable JavaScript to run this app. Matplotlib子图图例无法显示及首个子图放大方法求助
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib子图图例无法显示及首个子图放大方法求助

问题解决:Matplotlib子图空白图例与子图放大

一、空白图例的修复

空白图例是因为调用plot()时没指定label参数,图例找不到每条曲线对应的名称。另外你的代码里重复创建了子图对象(fig, (ax1, ax2)已经生成子图,后续plt.subplot(211)属于冗余操作),优化后的代码如下:

XWD_TO = data.iloc[:,0:1]
VAS_AX = data.iloc[:,1:2]
BTC_AUD = data.iloc[:,2:]

fig, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=True, figsize=(10, 8))
fig.suptitle('Daily Volatility')

# 第一个子图:添加label参数
ax1.set_title("XWD.TO and VAS.AX")
ax1.plot(XWD_TO, c='orange', label='XWD.TO')
ax1.plot(VAS_AX, c='green', label='VAS.AX')
ax1.legend(loc="upper right")

# 第二个子图
ax2.set_title("BTC-AUD")
ax2.plot(BTC_AUD, c='blue', label='BTC-AUD')
ax2.legend(loc="upper right")  # 可选:给第二个子图也加图例

plt.tight_layout()  # 自动调整子图间距,避免标题重叠
plt.show()

关键修改点:

  • 给每个plot()调用添加label参数,对应曲线名称
  • 移除冗余的plt.subplot(211)和plt.subplot(212),直接使用fig, (ax1, ax2)生成的子图对象

二、放大第一个子图

要让第一个子图高度更大,可以在创建子图时设置height_ratios参数,指定两个子图的高度比例:

# 设置height_ratios,比如第一个子图高度是第二个的2倍
fig, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=True, figsize=(10, 8), height_ratios=[2, 1])

# 后续绘图代码和上面一致
fig.suptitle('Daily Volatility')
ax1.set_title("XWD.TO and VAS.AX")
ax1.plot(XWD_TO, c='orange', label='XWD.TO')
ax1.plot(VAS_AX, c='green', label='VAS.AX')
ax1.legend(loc="upper right")

ax2.set_title("BTC-AUD")
ax2.plot(BTC_AUD, c='blue', label='BTC-AUD')
ax2.legend(loc="upper right")

plt.tight_layout()
plt.show()

这样第一个子图的高度会是第二个的2倍,实现“放大”的效果。如果需要更灵活的布局,也可以使用matplotlib.gridspec.GridSpec来精细控制子图尺寸。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:05:17