如何基于DataFrame按年份聚合后绘制分组柱状图?
解决方案
问题出在你没有先对数据按年份分组求和,直接用原始月度数据绘图,导致X轴挤满了所有月份,才出现拥挤的情况。按以下步骤修改即可:
1. 数据预处理:提取年份并按年度求和
先把Create Date列转为日期格式,提取年份作为分组依据,再对每个年份的count1-count4列求和:
import pandas as pd import matplotlib.pyplot as plt # 加载你的数据(示例数据与你提供的一致) data = { 'Create Date': ['2018-01', '2018-02', '2018-08', '2019-03', '2019-06', '2019-07', '2020-01', '2020-02', '2020-03', '2021-01', '2021-02', '2021-03', '2022-01', '2022-02', '2022-03'], 'count1': [12,11,12,13,15,16,12,12,12,11,12,11,17,18,19], 'count2': [21,25,26,28,22,25,25,23,26,28,29,22,21,23,23], 'count3': [12]*15, 'count4': [123,145,145,334,345,165,178,178,187,146,123,189,167,166,123] } df = pd.DataFrame(data) # 转换日期格式并提取年份 df['Create Date'] = pd.to_datetime(df['Create Date']) df['Year'] = df['Create Date'].dt.year # 按年份分组求和,仅保留count系列列 df_yearly = df.groupby('Year')[['count1', 'count2', 'count3', 'count4']].sum()
2. 绘制分组柱状图
用处理后的年度求和数据绘图,X轴会只显示2018-2022五个年份,每个年份下的四个柱子清晰对应各count列的年度总和:
df_yearly.plot.bar(figsize=(10,6), logy=True) plt.xticks(rotation=0) plt.xlabel('年份') plt.ylabel('求和值(对数刻度)') plt.title('各年度count指标求和对比') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.tight_layout() # 自动调整布局,避免图例或标签被截断 plt.show()
内容的提问来源于stack exchange,提问作者Mikasa
相关产品推荐
相关产品推荐

