首页 > 解决方案 > 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

我想制作一个 和 的堆积条形图ExpensesCommissions然后使该Income列成为该堆积列旁边的相邻条形图。

我熟悉该df.plot.bar()方法,但我不确定如何移动 x 轴值以使条形与堆叠和条形Income相邻ExpensesCommissions

标签: pandasdataframematplotlib

解决方案


您可以执行以下操作:首先生成堆积条形图,然后使用移位的 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')

在此处输入图像描述


推荐阅读