pandas 熊猫将数据框绘制为多个条形图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35248976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:38:53  来源:igfitidea点击:

pandas plot dataframe as multiple bar charts

pythonpandasmatplotlibplot

提问by jxn

This is my pandas dataframe df:

这是我的Pandas数据框df

          ab             channel   booked
0    control             book_it     466
1    control          contact_me     536
2    control             instant     17
3  treatment             book_it     494
4  treatment          contact_me     56
5  treatment             instant     22

I want to plot 3 groups of bar chart (according to channel):

我想绘制 3 组条形图(根据channel):

for each channel: plot control booked value vs treatment booked value.

对于每个渠道:绘制控制预订值与治疗预订值。

hence i should get 6 bar charts, in 3 groups where each group has control and treatment booked values.

因此我应该得到 6 个条形图,分为 3 个组,其中每个组都有控制和治疗预定值。

SO far i was only able to plot booked but not grouped by ab:

到目前为止,我只能绘制预定但不能按 ab 分组的图:

ax = df_conv['booked'].plot(kind='bar',figsize=(15,10), fontsize=12)
ax.set_xlabel('dim_contact_channel',fontsize=12)
ax.set_ylabel('channel',fontsize=12)
plt.show()

enter image description here

在此处输入图片说明

This is what i want (only show 4 but this is the gist): enter image description here

这就是我想要的(只显示 4 但这是要点): 在此处输入图片说明

回答by Stop harming Monica

Pivot the dataframe so control and treatment values are in separate columns.

旋转数据框,使控制值和处理值位于不同的列中。

df.pivot(index='channel', columns='ab', values='booked').plot(kind='bar')

bar plot

条形图