因此,我目前正在为Facebook的数据集建立聚类,并为每个行分别放置标签数据和每个聚类,并且数据框如下所示:
所以我想将数据绘制到堆积的条形图中 所以我对数据进行了分组
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)的堆叠条形图,它们是我拥有的集群?
答案 0 :(得分:1)
.unstack
分组数据帧dfff
。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')
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')