如何基于给定pandas DataFrame绘制分段堆叠条形图
实现分段堆叠条形图的完整方案
以下是可直接运行的完整实现代码:
import pandas as pd import matplotlib.pyplot as plt # 原始数据 df = pd.DataFrame( { 'Dates': ['2021-04-11', '2021-06-08', '2021-06-08', '2021-06-09', '2021-06-10', '2021-07-18', '2021-07-18'], 'Results': ['Negative', 'Invalid', 'Negative','Negative','Negative', 'Negative', 'Positive' ], 'Size': [1, 1, 1, 1, 4, 21, 2] }) # 数据聚合:按日期、检测结果分组求和,转换为适合绘图的宽表结构 df_pivot = df.groupby(['Dates', 'Results'])['Size'].sum().unstack(fill_value=0) # 绘制堆叠条形图 ax = df_pivot.plot(kind='bar', stacked=True, figsize=(10,6), color=['#ff9999','#66b3ff','#99ff99']) # 调整图表样式 plt.xlabel('日期', fontsize=12) plt.ylabel('总数量', fontsize=12) plt.title('各日期检测结果分布', fontsize=14) plt.xticks(rotation=45, ha='right') plt.legend(title='检测结果') # 可选:在堆叠区域中间标注对应数值 for c in ax.containers: ax.bar_label(c, label_type='center') plt.tight_layout() plt.show()
逻辑说明
- 先通过
groupby对同日期、同检测结果的Size字段求和,再用unstack将检测结果类型转换为列索引,得到的df_pivot每一行对应一个日期,每一列对应一种检测结果,值为该类别下的总Size - 直接调用pandas内置的plot方法,设置
stacked=True即可生成堆叠条形图,可自行调整配色、尺寸等参数匹配需求
内容的提问来源于stack exchange,提问作者shiva kumar
相关产品推荐
相关产品推荐

