我想制作一个 n 个元素的部分堆叠的条形图,其中 n -1个元素被堆叠,其余元素是与图的堆叠条形相邻的另一个条形等宽。相邻的条形图元素绘制在次要y轴上,通常为百分比,绘制在0和1之间。
我目前使用的解决方案能够很好地表示数据,但是我很好奇我如何才能获得在堆叠条形旁边的等宽单条形的预期结果。
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
mylabels=list('BCD')
df = pd.DataFrame(np.random.randint(1,11,size=(5,4)), columns=list('ABCD'))
df['A'] = list('abcde')
df['D'] = np.random.rand(5,1)
ax = df.loc[:,~df.columns.isin(['D'])].plot(kind='bar', stacked=True, x='A', figsize=(15,7))
ax2 = ax.twinx()
ax2.bar(df.A,df.D, color='g', width=.1)
ax2.set_ylim(0,1)
handles, labels = ax.get_legend_handles_labels()
green_patch = mpatches.Patch(color='g')
handles.append(green_patch)
ax.legend(handles=handles, labels=mylabels)
ax.set_xlabel('')
答案 0 :(得分:3)
让我们尝试传递align='edge'
和width
来控制小节的相对位置:
ax = df.drop('D', axis=1).plot.bar(x='A', stacked=True, align='edge', width=-0.4)
ax1=ax.twinx()
df.plot.bar(x='A',y='D', width=0.4, align='edge', ax=ax1, color='C2')
# manually set the limit so the left most bar isn't cropped
ax.set_xlim(-0.5)
# handle the legends
handles, labels = ax.get_legend_handles_labels()
h, l = ax1.get_legend_handles_labels()
ax.legend(handles=handles + h, labels=mylabels+l)
ax1.legend().remove()
输出: