如何用Matplotlib将两个推文情感分类条形图并排合并为一张图
实现方法
核心是用matplotlib的子图布局功能,创建1行2列的坐标轴容器,将两个条形图分别绘制到对应的坐标轴上即可。
完整可运行代码
import matplotlib.pyplot as plt import numpy as np # 请提前加载好你的df_navalny和df_putin数据集 # 创建1行2列的子图,总画布尺寸调整为12*5,匹配两个单图的尺寸总和 fig, (ax_left, ax_right) = plt.subplots(1, 2, figsize=(12, 5)) # 绘制左侧Navalny相关推文情感分类图 left_df = df_navalny (left_df.sentiment.value_counts()/len(left_df)*100).plot(kind="bar", rot=0, color=['#04407F','#0656AC','#0A73E1'], ax=ax_left) ax_left.set_title('Navalny相关推文情感分类', fontsize=15) ax_left.set_ylabel('Percentage [%]', fontsize=18) ax_left.set_yticks(np.arange(0, 110, 10)) ax_left.grid(color='#95a5a6', linestyle='-.', linewidth=1, axis='y', alpha=0.7) # 左侧双Y轴(对应原始计数) ax_left_twin = ax_left.twinx() ax_left_twin.set_yticks(np.arange(0, 110, 10)*len(left_df)/100) # 左侧柱子标注百分比 for p in ax_left.patches: ax_left.annotate('{:.2f}%'.format(p.get_height()), (p.get_x()+0.15, p.get_height()+1)) # 绘制右侧Putin相关推文情感分类图 right_df = df_putin (right_df.sentiment.value_counts()/len(right_df)*100).plot(kind="bar", rot=0, color=['#04407F','#0656AC','#0A73E1'], ax=ax_right) ax_right.set_title('Putin相关推文情感分类', fontsize=15) ax_right.set_ylabel('Percentage [%]', fontsize=18) ax_right.set_yticks(np.arange(0, 110, 10)) ax_right.grid(color='#95a5a6', linestyle='-.', linewidth=1, axis='y', alpha=0.7) # 右侧双Y轴(对应原始计数) ax_right_twin = ax_right.twinx() ax_right_twin.set_yticks(np.arange(0, 110, 10)*len(right_df)/100) # 右侧柱子标注百分比 for p in ax_right.patches: ax_right.annotate('{:.2f}%'.format(p.get_height()), (p.get_x()+0.15, p.get_height()+1)) # 自动调整子图间距,避免标签重叠 plt.tight_layout() plt.show()
额外调整说明
- 如果需要调整两个图的间距,可以在
plt.tight_layout()中传入w_pad参数,比如plt.tight_layout(w_pad=3)就会增加两个子图的水平间距 - 可以自行修改
figsize的数值调整整体画布的宽高 - 如果需要统一两个图的Y轴范围,可添加
ax_right.set_ylim(ax_left.get_ylim())保证二者刻度一致,更便于对比
内容的提问来源于stack exchange,提问作者DarleneDarlene
相关产品推荐
相关产品推荐

