如何在Python中基于多DataFrame绘制不同数据长度的分组条形图?
在同一张条形图中绘制不同长度类别的数据
需要在Python中实现:在同一张水平条形图上展示数据长度不同的多个类别。以下是我写的代码:
import pandas as pd import matplotlib.pyplot as plt Type_X = [200000, 150000] Type_Y = [168000, 120000] Comb = [192000] Cat = ['With Time Constraints', 'With Production Constraints'] Cat2 = ['Optimised Combination of Devices'] df = pd.DataFrame({'Type X': Type_X, 'Type Y': Type_Y,}, index=Cat) df2 = pd.DataFrame({'Comb' : Comb}, index=Cat2) print(df) print(df2) ax = plt.subplots() df.plot.barh(figsize = (15, 8), color={"Type X": "lightblue", "Type Y": "purple"}) df2.plot.barh(figsize = (15, 8), color={'Comb' : 'green'}) #annotate bars in bar plot for container in ax.containers: ax.bar_label(container) plt.title('SEC Weekly Profits of Devices under different Constraints', fontdict = {'fontsize': 20, 'fontweight': 'bold', 'color': 'black', 'verticalalignment': 'baseline', 'horizontalalignment': 'center'}) # export the file # plt.savefig("SEC_Weekly_Profit_Cons", dpi = 300) # Hide the right and top spines ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) # plot show plt.show()
期望的图表样式:
修正方案
当前代码存在几个问题:
ax = plt.subplots()错误接收了(figure, axes)元组,导致后续调用ax.containers时抛出属性错误;- 两次调用
plot.barh会生成独立的画布,无法将所有类别合并到同一张图; - 两个DataFrame的索引不统一,无法直接在同一轴上绘制。
修正后的完整代码:
import pandas as pd import matplotlib.pyplot as plt Type_X = [200000, 150000] Type_Y = [168000, 120000] Comb = [192000] # 定义所有类别标签 all_cats = ['With Time Constraints', 'With Production Constraints', 'Optimised Combination of Devices'] # 构建统一的DataFrame,缺失数据补0 df = pd.DataFrame({ 'Type X': [200000, 150000, 0], 'Type Y': [168000, 120000, 0], 'Comb': [0, 0, 192000] }, index=all_cats) # 创建画布和轴对象 fig, ax = plt.subplots(figsize=(15, 8)) # 在同一轴上绘制所有条形 df.plot.barh(ax=ax, color={"Type X": "lightblue", "Type Y": "purple", "Comb": "green"}) # 为每个条形添加数值标签 for container in ax.containers: ax.bar_label(container, fmt='%d') # 设置标题 ax.set_title('SEC Weekly Profits of Devices under different Constraints', fontdict={'fontsize': 20, 'fontweight': 'bold', 'color': 'black'}) # 隐藏右侧和顶部边框 ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) # 调整布局,防止标签被截断 plt.tight_layout() # 显示图表 plt.show()
核心调整点:
- 统一数据结构:将所有类别和对应数据整合到一个DataFrame中,缺失的类别数据补0,确保每个类别都有所有列的数值;
- 共享绘图轴:绘制时指定
ax=ax,让所有条形都渲染在同一个轴上; - 修正轴对象初始化:正确解构
plt.subplots()返回的画布和轴对象,避免属性调用错误; - 优化标签显示:用
fmt='%d'确保数值标签以整数形式展示,符合利润数据的直观性。
内容的提问来源于stack exchange,提问作者Seun Alabi
相关产品推荐
相关产品推荐

