pandas - 使用两列的组合自动化图形

时间:2018-01-11 15:00:52

标签: python pandas graph

在以下情况下,自动生成图表的最佳方法是什么:

  • 我在列
  • 中有一个具有不同计划和类型的数据框
  • 我想要一个计划和类型的每个组合的图表

数据帧:

plan type  hour  ok    notok  other 
A    cont   0    60.0  40.0    0.0    
A    cont   1    56.6  31.2    12.2    
A    vend   2    30.0  50.0    20.0    
B    test   5    20.0  50.0    30.0     

对于一个只有一个计划和类型的df,我写了以下代码:

fig_ = df.set_index('hour').plot(kind='bar', stacked=True, colormap='YlOrBr')
plt.xlabel('Hour')
plt.ylabel('(%)')
fig_.figure.savefig('p_hour.png', dpi=1000)
plt.show()

最后,我想为计划和类型的每个组合保存一个不同的数字。 提前谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用groupby尝试iterating over groups

for (plan, type), group in df.groupby(['plan', 'type']):
    fig_ = group.set_index('hour').plot(kind='bar', stacked=True, colormap='YlOrBr')
    plt.xlabel('Hour')  # Maybe add plan and type
    plt.ylabel('(%)')  # Maybe add plan and type
    fig_.figure.savefig('p_hour_{}_{}.png'.format(plan, type), dpi=1000)