[英]python stacked bar chart using categorical data
I have a Pandas dataframe (1800 obs) that looks something like this: 我有一个熊猫数据框(1800 obs),看起来像这样:
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. 我想创建一个堆叠的条形图,在x轴上具有列“ A”,“ B”,“ C”,“ D”,在y轴上具有该功能中每个级别的百分比。 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
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: 输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.