我正在尝试使用this site的College Scorecard数据在MatPlotLib中创建100%堆积的条形图.
一共有38列:
在[在这里插入学习范围]授予的学位百分比这解释了为什么有38个领域!
我有一部分学校想要为其做这张叠图.
我试图按照指示here.是的.这是很长的代码,但我想按书演奏. (此外,我一直对此博客很幸运)
这些数据与这些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)
in ()
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所大学,结果如下:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5CRWhmYt9CXt92YuIXdn1Waus2YhR3cuk2Lc9CX6MHc0RHaiojIsJye.png)
拥有10所大学,已经是一个繁忙的情节-拥有100所大学,这实际上是不可读的:
我可以保证,在将近8000所大学中,这种堆积的条形图将是完全不可读的.也许考虑另一种表示数据的方式?
标签:python,matplotlib,stacked-chart
来源: https://codeday.me/bug/20191010/1888624.html