[英]How to plot an horizontal barplot with percentage distribution from a pandas dataframe?
我有一個大的 pandas dataframe 像這樣:
在:
d = {'type': ['type 1', 'type 2', 'type 2', 'type 3', 'type 1', 'type 4', 'type 5', 'type 6', 'type 6', 'type 7' ], 'value': ['yes', 'no', 'yes', 'no', 'yes', 'no', 'yes','no', 'yes', 'no']}
df = pd.DataFrame(data=d)
df
出去:
type value
0 type: 1 yes
1 type: 2 no
2 type: 2 yes
3 type: 3 no
4 type: 1 yes
5 type: 4 no
6 type: 5 yes
7 type: 6 no
8 type: 6 yes
9 type: 7 no
如何創建一個水平條形圖,每個條形圖中是/否值的百分比? 到目前為止,我試圖:
sns.barplot(x='type', y='value', data=df, orient = 'h')
但是,對於每個是/否值,我只得到沒有百分比分布的條形圖。 如何在不拆分的情況下將其繪制在同一個欄中? 例如:
在上面的示例中,yes/no 的總數位於 x 軸上。
您可以使用pd.crosstab
計算百分比,然后使用plot.barh
到 plot 條形:
ax = (pd.crosstab(df['type'], df['value'], normalize='index')
.plot.barh(stacked=True, alpha=0.8)
)
Output:
有關條形圖上的數字,請查看此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.