如何使用df.groupby.plot.bar将3个柱状图横向并排展示?
横向并排展示三个柱状图的实现方案
你可以通过matplotlib的subplots创建子图布局,然后将每个pandas绘制的柱状图指定到对应的子图axes上,具体代码如下:
import matplotlib.pyplot as plt # 创建1行3列的子图布局,获取画布和axes数组 fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 5)) # 第一个柱状图绘制到第一个axes df.groupby([df.col1, pd.cut(df.col2, [0,1,2])]).col2.mean().plot.bar(ax=axes[0]) axes[0].set_title('第一个子图') axes[0].set_xlabel('分组') axes[0].set_ylabel('均值') # 第二个柱状图绘制到第二个axes df1.groupby([df1.col1, pd.cut(df1.col2, [0,1,2])]).col2.mean().plot.bar(ax=axes[1]) axes[1].set_title('第二个子图') axes[1].set_xlabel('分组') # 第三个柱状图绘制到第三个axes df2.groupby([df2.col1, pd.cut(df2.col2, [0,1,2])]).col2.mean().plot.bar(ax=axes[2]) axes[2].set_title('第三个子图') axes[2].set_xlabel('分组') # 自动调整布局,避免标签重叠 plt.tight_layout() plt.show()
关键说明:
subplots(nrows=1, ncols=3)创建1行3列的子图网格,axes是包含3个axes对象的数组,对应三个子图位置- 每个
plot.bar()通过ax参数指定目标axes,实现三个图横向并排 figsize可根据需求调整画布尺寸,保证图表显示清晰tight_layout()自动调整子图间距,防止标题、坐标轴标签互相重叠
另外注意你原代码里的pd.cut[0,1,2]是语法错误,正确写法为pd.cut(目标列, [0,1,2]),上述代码已修正该问题。
内容的提问来源于stack exchange,提问作者jds
相关产品推荐
相关产品推荐

