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

如何在Matplotlib绘制子图时仅显示一行图例?

解决方法

问题出在fig.legend()默认会收集所有子图的图例条目,而你的4个子图图例标识完全一致,所以才会重复显示4组相同内容。你只需要从任意一个子图中提取唯一的图例元素,再传给全局图例即可:

修改后的代码如下:

def plot(self, concat_series, save_plot):
    grouped = concat_series.groupby("metric")

    fig, axes = plt.subplots(nrows=1, ncols=len(grouped))
    i=0
    for name, group in grouped:
        group.plot.bar(ax=axes[i], x='network', legend=False)
        axes[i].set_title(name)
        axes[i].grid(True)  # Add grid lines (optional)
        i+=1

    plt.tight_layout()  # Adjust spacing (optional)
    # 从第一个子图提取唯一的图例元素
    handles, labels = axes[0].get_legend_handles_labels()
    # 用这些元素创建全局图例,仅显示一组
    legend = fig.legend(handles=handles, labels=labels, loc="lower center", ncol=4, title="Coordinates")
    plt.savefig(save_plot)
    plt.close()

原理很简单:所有子图对应的图例系列完全一致,所以只需要取其中一个子图的handles(图例图标)和labels(图例文字),就能生成唯一的全局图例,不会出现重复条目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 11:07:04