使用pandas subplots=True绘图时如何设置所有子图的图例字体大小
解决方案
plt.legend()默认仅作用于当前激活的最后一个子图,因此仅最后一个子图的图例配置生效。你使用subplots=True返回的ax为所有子图对象组成的数组,遍历该数组逐个设置子图图例即可适配任意列数的场景:
def plot_subplot(df, group): ax = df.plot(subplots=True, fontsize=20, figsize=(80,40)) # 遍历所有子图,逐个设置图例属性 for sub_ax in ax: sub_ax.legend(loc='best', prop={'size': 30}) ax[0].get_figure().savefig("{}.png".format(group), bbox_inches='tight', dpi=100)
可选优化
如果不需要每个子图独立展示图例,想要整幅图统一展示一个全局图例,可以参考如下写法:
def plot_subplot(df, group): ax = df.plot(subplots=True, fontsize=20, figsize=(80,40), legend=False) # 提取所有列名作为全局图例标签 handles, labels = ax[0].get_legend_handles_labels() # 在画布顶部添加统一全局图例 ax[0].get_figure().legend(handles, labels, loc='upper center', ncol=len(labels), prop={'size': 30}) ax[0].get_figure().savefig("{}.png".format(group), bbox_inches='tight', dpi=100)
内容的提问来源于stack exchange,提问作者very_young
相关产品推荐
相关产品推荐

