用于按值分组的python堆栈堆叠的条形图

时间:2020-09-01 06:03:18

标签: python matplotlib seaborn

因此,我目前正在为Facebook的数据集建立聚类,并为每个行分别放置标签数据和每个聚类,并且数据框如下所示:

enter image description here

所以我想将数据绘制到堆积的条形图中 所以我对数据进行了分组

dfff=x_df.groupby("cluster")["page_type"].value_counts()

和类似的输出

cluster  page_type 
0        government    5387
         company       3231
         politician    3149
         tvshow        1679
1        government     563
         company          9
         politician       2
2        company       3255
         politician    2617
         tvshow        1648
         government     930
Name: page_type, dtype: int64

那么如何将这个系列绘制成3列(0,1,2)的堆叠条形图,它们是我拥有的集群?

1 个答案:

答案 0 :(得分:1)

import pandas as pd
import matplotlib.pyplot as plt

# given dfff and a groupby dataframe
dfp = dfff.unstack()

# display(dfp)
page_type  company  government  politician  tvshow
id                                                
0           3231.0      5387.0      3149.0  1679.0
1              9.0       563.0         2.0     NaN
2           3255.0       930.0      2617.0  1648.0

# plot stacked bar
dfp.plot.bar(stacked=True)
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')

enter image description here

古朴的外观

import matplotlib.pyplot as plt

# set style parameter
plt.style.use('seaborn')

# plot stacked bar
dfp.plot.bar(stacked=True)
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')

enter image description here