首页 > 解决方案 > 带有空列的堆积条形图

问题描述

我正在尝试做一个堆积条形图。我可以做一个基本的条形图:

df = pd.DataFrame({'Y': [1,1,1,1,1,2,3,2],
                   'X': [2,2,2,2,3,3,3,4]})

Y_1 = df.loc[df['Y'] == 1]
Y_2 = df.loc[df['Y'] == 2]

Count_0 = df.groupby(['X']).size().to_frame('Count').reset_index()
Count_1 = Y_1.groupby(['X']).size().to_frame('Count').reset_index()
Count_2 = Y_2.groupby(['X']).size().to_frame('Count').reset_index()

height_0 = Count_0.Count
height_1 = Count_1.Count
height_2 = Count_2.Count
bars     = Count_0.X

fig, (ax1) = plt.subplots(1,1);

y_pos = np.arange(len(bars))

p1 = plt.bar(y_pos, height_0) 

for item in ([ax1.title, ax1.xaxis.label, ax1.yaxis.label] +
             ax1.get_xticklabels() + ax1.get_yticklabels()):
    item.set_fontsize(22)

plt.xlabel('X')
plt.ylabel('Count')
plt.xticks(y_pos, bars)
plt.yticks(np.arange(0, 4.1, 1))
fig = plt.gcf()
fig.set_size_inches(18.5, 10.5)
plt.show()
plt.clf()

在此处输入图像描述 但是当我尝试按“Y”类堆叠它时:

p2 = plt.bar(y_pos, height_2, bottom = height_1)

我得到:

ValueError: incompatible sizes: argument 'height' must be length 3 or scalar

我认为问题可能是由于这些类没有任何 X = 2 的实例,因此存在 Y = 2 和 Y = 3 的空列。我希望 X 轴上的 X 和 Y 成为颜色!

标签: pandasmatplotlib

解决方案


IIUC,你想要这个:

df = pd.DataFrame({'Y': [1,1,1,1,1,2,3,2],
                   'X': [2,2,2,2,3,3,3,4]})
df.groupby(['X','Y'])['Y'].count().unstack().plot.bar(stacked=True)

输出:

在此处输入图像描述


推荐阅读