汇总一列的Python绘图条形图,按两个不同的列分组

时间:2019-04-04 17:05:57

标签: python pandas matplotlib

我有一个数据集:

Year Month Category Count Line
2019   1       a      2    5
2019   2       b      5    7
2018   1       a      7    12

我想按时间顺序绘制条形图,其中y轴是Count字段的总和,而Line列有一个单独的辅助轴(无总和)。

创建分组和求和时遇到麻烦。

1 个答案:

答案 0 :(得分:0)

尝试:

df['SumCount'] = df.groupby('Year')['Count'].transform('sum')
ax=df.plot(kind='bar', x='Year',y='Line', alpha=.7, color='g', position=1, width =.2)
df.plot(kind='bar', x='Year',y='SumCount', ax=ax, secondary_y=True, alpha=.8, position=0, width=.2)

输出:

enter image description here

相关问题