使用分类数据的python堆积条形图 [英] python stacked bar chart using categorical data
本文介绍了使用分类数据的python堆积条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Pandas 数据框(1800 obs),看起来像这样:
A B C D1 CL0 CL1 CL2 CL02 CL2 CL1 CL1 CL33 CL3 CL2 CL0 CL1.……………….………………n CL2 CL1 CL0 CL3
我想创建一个堆积条形图,在 x 轴上有A"、B"、C"、D"列,在 y 轴上有该特征中每个级别的百分比.类似于下图.
我猜我需要以某种方式将数据制成表格?但我不知道该怎么做.
解决方案
print(df)
输出:
A B C D1 CL0 CL1 CL2 CL02 CL2 CL1 CL1 CL33 CL3 CL2 CL0 CL1
使用
I have a Pandas dataframe (1800 obs) that looks something like this:
A B C D
1 CL0 CL1 CL2 CL0
2 CL2 CL1 CL1 CL3
3 CL3 CL2 CL0 CL1
. ... ... ... ...
. ... ... ... ...
n CL2 CL1 CL0 CL3
I want to create a stacked bar chart that will have columns 'A', 'B', 'C', 'D' on the x axis, and the percentage of each level in that feature on the y axis. Something like the picture below.
I'm guessing I need to tabulate the data somehow? But I don't know how to do this.
解决方案
print(df)
Output:
A B C D
1 CL0 CL1 CL2 CL0
2 CL2 CL1 CL1 CL3
3 CL3 CL2 CL0 CL1
Using .apply()
counts = df.apply(lambda x: x.value_counts() / len(x)).transpose()
fig = plt.figure()
ax = fig.add_subplot(111)
counts.plot(ax=ax,kind='bar', stacked=True, rot=0)
vals = ax.get_yticks()
ax.set_yticklabels(['{:3.2f}%'.format(x*100) for x in vals])
ax.yaxis.grid(True)
ax.set_axisbelow(True)
plt.show()
Output:
这篇关于使用分类数据的python堆积条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文