让我们说我拥有以下熊猫数据框:
>> 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
和{ {1}}条
答案 0 :(得分:2)
您可以执行以下操作:首先生成堆叠的条形图,然后使用移位的x值,其中移位等于堆叠的条形宽度。另外,您可以根据需要使用this方法为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')