[英]100% Stacked Bar Chart in MatPlotLib
我正在嘗試使用此站點的College Scorecard數據在MatPlotLib中創建100%Stacked Bar Chart。
有38列:在[插入研究區域]中授予的學位百分比這解釋了為什么有38個領域!
而且我有一些學校的子集,我想為此做疊加圖表。
我試着按照這里的說明操作。 是。 這是很長的代碼,但我想通過這本書來播放它。 (加上我一直對這個博客好運)數據來自這些PCIP(按學習領域授予的學位百分比),以百分比形式出現,因此我沒有必須按照Chris的計算,因為它們已經完成。
我運行代碼時遇到錯誤:
bar_width = 1
bar_l = [i for i in range(len(df['PCIP01']))]
tick_pos = [i+(bar_width/2) for i in bar_l]
# Create a figure with a single subplot
f, ax = plt.subplots(1, figsize=(10,5))
ax.bar(bar_l,
degrees.PCIP01,
label='PCIP01',
alpha=0.9,
color='#2D014B',
width=bar_width
)
ax.bar(bar_l,
PCIP04,
label='PCIP04',
alpha=0.9,
color='#28024E',
width=bar_width
)
[等等剩下的所有36個領域等等
# Set the ticks to be School names
plt.xticks(tick_pos, degrees['INSTNM'])
ax.set_ylabel("Percentage")
ax.set_xlabel("")
# Let the borders of the graphic
plt.xlim([min(tick_pos)-bar_width, max(tick_pos)+bar_width])
plt.ylim(-10, 110)
# rotate axis labels
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
# shot plot
這是我收到的錯誤:
ValueError Traceback (most recent call last)
<ipython-input-91-019d33be36c2> in <module>()
7 alpha=0.9,
8 color='#2D014B',
----> 9 width=bar_width
10 )
11 ax.bar(bar_l,
C:\Users\MYLOCATION\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
1889 warnings.warn(msg % (label_namer, func.__name__),
1890 RuntimeWarning, stacklevel=2)
-> 1891 return func(ax, *args, **kwargs)
1892 pre_doc = inner.__doc__
1893 if pre_doc is None:
C:\Users\MYLOCATION\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in bar(self, left, height, width, bottom, **kwargs)
2077 if len(height) != nbars:
2078 raise ValueError("incompatible sizes: argument 'height' "
-> 2079 "must be length %d or scalar" % nbars)
2080 if len(width) != nbars:
2081 raise ValueError("incompatible sizes: argument 'width' "
ValueError: incompatible sizes: argument 'height' must be length 38678 or scalar
任何人都可以幫助我簡化這段代碼,這樣我就可以創建這個堆疊的100%條形圖嗎?
首先,這個數據集中有很多大學,也許堆積條形圖不是最好的主意?
無論如何,你可以遍歷每種類型的學位並添加另一個學位。 要創建堆疊條,只需更改每個條的底部位置即可。
import pandas as pd
import matplotlib.pyplot as plt
from cycler import cycler
import numpy as np
df = pd.read_csv('scorecard.csv')
df = df.ix[0:10]
degList = [i for i in df.columns if i[0:4]=='PCIP']
bar_l = range(df.shape[0])
cm = plt.get_cmap('nipy_spectral')
f, ax = plt.subplots(1, figsize=(10,5))
ax.set_prop_cycle(cycler('color',[cm(1.*i/len(degList)) for i in range(len(degList))]))
bottom = np.zeros_like(bar_l).astype('float')
for i, deg in enumerate(degList):
ax.bar(bar_l, df[deg], bottom = bottom, label=deg)
bottom += df[deg].values
ax.set_xticks(bar_l)
ax.set_xticklabels(df['INSTNM'].values, rotation=90, size='x-small')
ax.legend(loc="upper left", bbox_to_anchor=(1,1), ncol=2, fontsize='x-small')
f.subplots_adjust(right=0.75, bottom=0.4)
f.show()
您可以修改此代碼以獲得您想要的內容(例如,您似乎需要百分比而不是分數,因此只需將每個度數列乘以100)。 為了測試我參加了前10個大學,這導致了這個情節:
有10所大學已經是一個非常繁忙的地塊 - 擁有100所大學幾乎是不可讀的:
我可以保證,有近8000所大學,這個堆積的條形圖將是完全不可讀的。 也許考慮另一種表示數據的方式?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.