简体   繁体   English

使用 Pandas/matplotlib.pyplot 在 python 中绘制堆积条形图

[英]Plotting a stacked Barcharts in python using Pandas/matplotlib.pyplot

I am trying to create a stacked bar plots with each bar represent a state, and within each bar, there are three categories of sales orders by counts: Office supplies, Furniture, and Technology.我正在尝试创建一个堆叠的条形图,每个条形代表一个 state,在每个条形中,按数量分为三类销售订单:办公用品、家具和技术。 if anyone can help one this, just getting started on visuals using python!如果有人能帮上忙,那就开始使用 python 进行视觉效果吧!

在此处输入图像描述

Use crosstab with DataFrame.plot.bar with stacked=True parameter:crosstabDataFrame.plot.bar结合使用,参数为 packed stacked=True

df = pd.DataFrame({
        'Category':list('ffofofoftoof'),
        'State':list('kkcffccccccc')
})
print (df)
   Category State
0         f     k
1         f     k
2         o     c
3         f     f
4         o     f
5         f     c
6         o     c
7         f     c
8         t     c
9         o     c
10        o     c
11        f     c

df1 = pd.crosstab(df['State'], df['Category'])
print (df1)
Category  f  o  t
State            
c         3  4  1
f         1  1  0
k         2  0  0

df1.plot.bar(stacked=True)

G

Assuming you have stored the data in a pandas dataframe df - you can use pandas bar plot to achieve the desired result. Assuming you have stored the data in a pandas dataframe df - you can use pandas bar plot to achieve the desired result.

df.groupby(['State', 'Category'])['Category'].count().unstack().plot(kind='bar', stacked=True)

You can get more information about bar plot from pandas and matplotlib documentation.您可以从 pandas 和 matplotlib 文档中获取有关 bar plot 的更多信息。

Matplotlib stacked bar chart Matplotlib 堆积条形图

Pandas bar chart Pandas条形图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM