![](/img/trans.png)
[英]How to make stacked bar plot of dataframe values as percentage in matplotlib/pandas
[英]How to create a stacked percentage bar graph from a dataframe with percentage values in Python?
我有以下數據框:
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
如何創建堆疊的垂直條形圖,其中y的范圍為0-100%,並繪制百分比數據? 我還想添加帶有與類對應的顏色的圖例。
我嘗試過的代碼:
df.T.plot(kind='bar',stacked=True)
結果錯誤: TypeError: Empty 'DataFrame': no numeric data to plot
classgraph,texts = plt.bar(df["Percentage"],height=5) #added texts for later legend
給了錯誤:
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)
我閱讀了很多有關如何執行此操作的文章,但似乎無法弄清楚。
好吧,假設您有此數據框
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
如果繪制它,結果將是混亂的。
df.set_index('Class').T.plot(kind='bar', stacked=True)
為了解決該問題,您需要計算每列的百分比。 然后將其繪制。
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.