pandas - 带有空列的堆积条形图
问题描述
我正在尝试做一个堆积条形图。我可以做一个基本的条形图:
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
我认为问题可能是由于这些类没有任何 X = 2 的实例,因此存在 Y = 2 和 Y = 3 的空列。我希望 X 轴上的 X 和 Y 成为颜色!
解决方案
推荐阅读
- c++ - 如何在 C++ 中获取当前文件路径?
- swift - 滑块只增加图像视图大小而不是减小大小
- powershell - 使用 powershell 脚本访问 Outlook 邮件
- php - 当结果为 9 时处理未定义的偏移错误
- javascript - 如何处理在 AWS ec2 上使用“serve-s build”构建和运行的 create-react-app 引导应用程序的后端 API 请求?
- c++ - 我可以擦除 std::queue 中间的节点吗?
- c# - Unity:定义一个新类新类
- r - R 中的圆形堆叠条形图 - 美学长度必须为 1 或与数据相同 (26)
- ruby-on-rails - Docker-compose 未将依赖容器添加到 /etc/hosts
- xml - XML 文件需要在我的 C 盘上打开一个 .exe,但路径中有一个 &。失败