我正在尝试使用来自 this site 的大学记分卡数据在 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)
<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 所大学中,这种堆积条形图将完全不可读。也许考虑另一种表示数据的方式?
关于python - MatPlotLib 中的 100% 堆叠条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43566956/