天天看點

python百分比堆積條形圖_python-MatPlotLib中100%堆積的條形圖

我正在嘗試使用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所大學,結果如下:

python百分比堆積條形圖_python-MatPlotLib中100%堆積的條形圖

擁有10所大學,已經是一個繁忙的情節-擁有100所大學,這實際上是不可讀的:

python百分比堆積條形圖_python-MatPlotLib中100%堆積的條形圖

我可以保證,在将近8000所大學中,這種堆積的條形圖将是完全不可讀的.也許考慮另一種表示資料的方式?

标簽:python,matplotlib,stacked-chart

來源: https://codeday.me/bug/20191010/1888624.html