Matplotlib绘制并列双条形图:右侧图表排序与Y轴标签问题
问题解决:Matplotlib并列条形图排序与Y轴标签修复
核心问题分析
你当前的代码存在两个关键问题:
- 右侧图表复用了左侧的数据集(
merge[:30]),未单独提取mentioned_user列的前10最大值,导致排序不符合要求 - 设置了
sharey=True强制共享Y轴,使得右侧无法显示独立的Y轴标签
分步解决方案
1. 分别提取两列的前10最大值并排序
为左右图表分别筛选对应列的Top10数据,并按升序排列(适配横向条形图从下到上数值递增的展示逻辑):
- 左图数据:按
username列降序取前10,再反转成升序,保证绘图时从下到上数值变大 - 右图数据:按
mentioned_user列降序取前10,再反转成升序
2. 关闭Y轴共享,设置独立Y轴标签
去掉plt.subplots中的sharey=True参数,让两个图表拥有独立Y轴,再分别为左右轴设置对应刻度标签。
修正后的完整代码
# 分别提取两列的Top10数据并排序 # 左图:username列前10最大值,升序排列 top10_username = merge.sort_values('username', ascending=False).head(10).sort_values('username', ascending=True) # 右图:mentioned_user列前10最大值,升序排列 top10_mentioned = merge.sort_values('mentioned_user', ascending=False).head(10).sort_values('mentioned_user', ascending=True) font_color = '#525252' hfont = {'fontname':'Calibri'} facecolor = '#eaeaf2' color_red = '#fd625e' color_blue = '#01b8aa' title0 = 'Spreading Hate' title1 = 'Receiving Hate' # 去掉sharey=True,让两个图表拥有独立Y轴 fig, axes = plt.subplots(figsize=(12,6), facecolor=facecolor, ncols=2) fig.tight_layout(pad=3) # 绘制左图 axes[0].barh(top10_username.index, top10_username['username'], align='center', color=color_red, zorder=10) axes[0].set_title(title0, fontsize=18, pad=15, color=color_red, **hfont) axes[0].set_yticks(top10_username.index) axes[0].set_yticklabels(top10_username.index) axes[0].yaxis.tick_left() # 绘制右图 axes[1].barh(top10_mentioned.index, top10_mentioned['mentioned_user'], align='center', color=color_blue, zorder=10) axes[1].set_title(title1, fontsize=18, pad=15, color=color_blue, **hfont) axes[1].set_yticks(top10_mentioned.index) axes[1].set_yticklabels(top10_mentioned.index) axes[1].yaxis.tick_right() # 设置刻度样式 axes[0].tick_params(axis='y', colors='black') for label in (axes[0].get_xticklabels() + axes[0].get_yticklabels()): label.set(fontsize=13, color=font_color, **hfont) for label in (axes[1].get_xticklabels() + axes[1].get_yticklabels()): label.set(fontsize=13, color=font_color, **hfont) # 调整子图间距,避免标签重叠 plt.subplots_adjust(wspace=0.3, top=0.85, bottom=0.1, left=0.15, right=0.85) filename = 'politicians_spread_vs_receive_hate' plt.savefig(filename+'.png', facecolor=facecolor, dpi=300) plt.show()
关键修改说明
- 新增
top10_username和top10_mentioned两个数据集,分别对应两列的Top10升序数据 - 移除
sharey=True,允许右侧图表显示独立的Y轴标签 - 调整图表尺寸和子图间距,避免标签重叠
- 分别为两个图表设置各自的Y轴刻度和标签
内容的提问来源于stack exchange,提问作者Maxl Gemeinderat
相关产品推荐
相关产品推荐

