[英]How to plot an horizontal barplot with percentage distribution from a pandas dataframe?
I have a large pandas dataframe like this:我有一个大的 pandas dataframe 像这样:
In:在:
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
Out:出去:
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
How can I create an horizontal barplot with the percentage of yes/no values in each bar?如何创建一个水平条形图,每个条形图中是/否值的百分比? So far I tried to:到目前为止,我试图:
sns.barplot(x='type', y='value', data=df, orient = 'h')
However, I only get the bars with no percentage of the distribution for each yes/no value.但是,对于每个是/否值,我只得到没有百分比分布的条形图。 How can I draw it in the same bar without splitting it?如何在不拆分的情况下将其绘制在同一个栏中? For example:例如:
In the above example, the total count of yes/no is in the x axis.在上面的示例中,yes/no 的总数位于 x 轴上。
You can use pd.crosstab
to compute the percentage, then plot.barh
to plot the bars:您可以使用pd.crosstab
计算百分比,然后使用plot.barh
到 plot 条形:
ax = (pd.crosstab(df['type'], df['value'], normalize='index')
.plot.barh(stacked=True, alpha=0.8)
)
Output: Output:
For the numbers on bars, have a look at this question .有关条形图上的数字,请查看此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.