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

如何在Matplotlib图例中忽略第一个子图的曲线条目?

解决方法

有两种可行的方式可以实现你的需求,既不打乱颜色匹配,又能隐藏第一个子图对应的图例条目:


方法一:直接排除第一个子图的曲线(更简洁)

你可以只收集需要展示的子图(ax2、ax3、ax4)的曲线对象,然后基于这些对象创建图例,完全跳过ax1的曲线。这样图例中就不会出现第一个空条目,同时颜色匹配完全正确。

修改代码如下:

warped_values = values_to_warp * factors
print(warped_values.shape)
fig = plt.figure(figsize=(8.33, 2.5), dpi=300, constrained_layout=True)
fig.supxlabel("Sample points", fontsize=9)
ax1 = fig.add_subplot(1,4,1)
ax2 = fig.add_subplot(1,4,2)
ax3 = fig.add_subplot(1,4,3, sharey=ax2)
ax4 = fig.add_subplot(1,4,4, sharey=ax2)
for ax in [ax1, ax2, ax3]:
    ax.tick_params(axis='both', which='major', labelsize=9)

ax1.plot(factors_vec, lw=0.85)
ax1.set_title("Curve with mean in (0.85, 1.15)", fontsize=9)
ax2.plot(values_to_warp, lw=0.85)
ax2.set_title("Motion data", fontsize=9)
ax3.plot((warped_values), lw=0.85)
ax3.set_title("Motion data warped", fontsize=9)

ax4.plot(values_to_warp - warped_values, lw=0.85)
ax4.set_title("Difference", fontsize=9)

# 收集ax2、ax3、ax4的曲线对象
handles = []
for ax in [ax2, ax3, ax4]:
    handles.extend(ax.get_lines())

# 基于收集到的曲线和movement_columns创建图例
fig.legend(handles=handles, labels=movement_columns, loc='upper center', bbox_to_anchor=(0.5, -0.05),
fancybox=True, shadow=True, ncol=3, fontsize=8)

方法二:隐藏图例中的第一个条目

如果你想保留原有的图例创建逻辑,只是隐藏第一个空条目对应的曲线,可以在创建图例后,修改第一个图例项的可见性:

修改代码如下:

warped_values = values_to_warp * factors
print(warped_values.shape)
fig = plt.figure(figsize=(8.33, 2.5), dpi=300, constrained_layout=True)
fig.supxlabel("Sample points", fontsize=9)
ax1 = fig.add_subplot(1,4,1)
ax2 = fig.add_subplot(1,4,2)
ax3 = fig.add_subplot(1,4,3, sharey=ax2)
ax4 = fig.add_subplot(1,4,4, sharey=ax2)
for ax in [ax1, ax2, ax3]:
    ax.tick_params(axis='both', which='major', labelsize=9)

ax1.plot(factors_vec, lw=0.85)
ax1.set_title("Curve with mean in (0.85, 1.15)", fontsize=9)
ax2.plot(values_to_warp, lw=0.85)
ax2.set_title("Motion data", fontsize=9)
ax3.plot((warped_values), lw=0.85)
ax3.set_title("Motion data warped", fontsize=9)

ax4.plot(values_to_warp - warped_values, lw=0.85)
ax4.set_title("Difference", fontsize=9)

# 创建图例并保存对象引用
leg = fig.legend([""] + movement_columns, loc='upper center', bbox_to_anchor=(0.5, -0.05),
fancybox=True, shadow=True, ncol=3, fontsize=8)

# 隐藏第一个图例条目对应的曲线
leg.legendHandles[0].set_visible(False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:54:59