[英]How to create a stacked percentage bar graph from a dataframe with percentage values in Python?
I have following dataframe: 我有以下数据框:
Class Percentage
class1 0.215854
class2 0.12871
class3 0.122787
class4 0.0680061
class5 0.0670523
class6 0.0826716
class7 0.309828
class8 0
class9 0
How can I create a stacked vertical bar graph where y goes from 0-100% and the percentage data is plotted? 如何创建堆叠的垂直条形图,其中y的范围为0-100%,并绘制百分比数据? I would also like to add a legend with a color corresponding to a class.
我还想添加带有与类对应的颜色的图例。
Code I've tried: 我尝试过的代码:
df.T.plot(kind='bar',stacked=True)
results in error: TypeError: Empty 'DataFrame': no numeric data to plot
结果错误:
TypeError: Empty 'DataFrame': no numeric data to plot
classgraph,texts = plt.bar(df["Percentage"],height=5) #added texts for later legend
gave error: 给了错误:
Traceback (most recent call last):
File "<ipython-input-71-894dc447893f>", line 1, in <module>
classgraph,texts = plt.bar(dataframe_plot["Percentage"],height=5)
ValueError: too many values to unpack (expected 2)
I read quite some posts on how to do this but I can't seem to figure it out. 我阅读了很多有关如何执行此操作的文章,但似乎无法弄清楚。
Well, let's say you have this dataframe 好吧,假设您有此数据框
import pandas as pd
import seaborn as sns
sns.set_style("darkgrid")
data = {'Class': ['class1', 'class2', 'class3'],
'mid-term': [345, 123, 74],
'final':[235, 345, 632]}
df = pd.DataFrame(data)
df.head()
# Class mid-term final
#0 class1 345 235
#1 class2 123 345
#2 class3 74 632
If you plot it, the results will be messy. 如果绘制它,结果将是混乱的。
df.set_index('Class').T.plot(kind='bar', stacked=True)
In order to solve the problem, you need to calculate the percentage for each column. 为了解决该问题,您需要计算每列的百分比。 Then plot it.
然后将其绘制。
df['mid-per'] = (df['mid-term'] / df['mid-term'].sum() * 100)
df['final-per'] = (df['final'] / df['final'].sum() * 100)
df.set_index('Class')[['mid-per', 'final-per']].T.plot(kind='bar', stacked=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.