pandas - Pandas:带有相邻条形的堆积条形图
问题描述
假设我有以下 Pandas 数据框:
>> df
Period Income Expenses Commissions
0 12034.23 1665.25 601.59
1 23432.77 2451.33 1521.4
2 62513.12 4210.35 3102.24
我想制作一个 和 的堆积条形图Expenses
,Commissions
然后使该Income
列成为该堆积列旁边的相邻条形图。
我熟悉该df.plot.bar()
方法,但我不确定如何移动 x 轴值以使条形与堆叠和条形Income
相邻Expenses
Commissions
解决方案
您可以执行以下操作:首先生成堆积条形图,然后使用移位的 x-values,其中移位等于堆积条的宽度。Income
此外,如果您愿意,可以添加使用此方法的额外图例
import matplotlib.patches as mpatches
import numpy as np
bar_width = 0.25
fig, ax = plt.subplots()
df[['Expenses', 'Commissions']].plot(kind='bar', stacked=True, ax=ax, width=bar_width)
ax.bar(np.arange(len(df))+bar_width, df['Income'], align='center', width=bar_width, color='green')
ax.set_xlim(-0.5, 2.5)
handles, labels = ax.get_legend_handles_labels()
patch = mpatches.Patch(color='green', label='Income')
handles.append(patch)
plt.legend(handles=handles, loc='best')
推荐阅读
- spring - RestTemplate 确实在对象中发送空值
- php - Strava Api 问题
- python - MacOs 上的 PyOpenGL OpenGL 版本
- node.js - 在树莓派上的节点 js 脚本中读取环境变量时出错
- java - 模拟 POST HTTP 请求获取空指针异常
- java - 杰克逊将 GeoJsonPoint 序列化为纬度/经度
- database - 发现之前没有 $ref 的 $id 字段,这是无效的
- java - Mapreduce函数计算入度和出度并使用java显示总和
- javascript - 输入新值时,如何将变量重新设置为从头开始计数?
- sql - 从同一张表的子查询中选择 Id+1