如何在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
相关产品推荐
相关产品推荐

