MatPlotLib中的100%堆积条形图

5

我正在尝试使用此网站的College Scorecard数据,在MatPlotLib中创建100%堆积条形图。

有38个列,它们是:[插入研究领域]获得学位的百分比,这就解释了为什么有38个字段!

我有一些子集的学校需要做这个堆积图。

我试图按照这里的说明去做。是的。代码相当冗长,但我想要按部就班地操作。(再加上我总是对这个博客好运)由于数据已经以百分比形式给出,所以我不必像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% 条形图吗?
1个回答

3

首先,这个数据集中有很多大学,也许堆叠条形图不是最好的选择?

无论如何,您可以循环遍历每种类型的学位并添加另一个条形图。要创建堆叠条形图,只需更改每个条形图的底部位置。

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所大学,结果如下图所示: enter image description here 仅使用10所大学就已经是一个相当繁忙的图形 - 100所大学则几乎无法阅读: enter image description here 我可以保证,对于近8000所大学,这种堆积条形图将完全无法阅读。也许考虑另一种表示数据的方式?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接