【发布时间】:2019-04-18 13:45:22
【问题描述】:
我正在尝试制作堆积条形图。我可以做一个基本的条形图:
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()
p2 = plt.bar(y_pos, height_2, bottom = height_1)
我明白了:
ValueError: incompatible sizes: argument 'height' must be length 3 or scalar
我认为问题可能在于存在 Y = 2 和 Y = 3 的空列,因为这些类没有任何 X = 2 的实例。 我希望 X 轴上的 X 和 Y 是颜色!
【问题讨论】:
标签: pandas matplotlib