Python 如何创建部分堆叠的条形图
我想做一个n个元素的部分堆叠条形图,其中n-1个元素被堆叠,剩余的元素是另一个与相同宽度的堆叠条形相邻的条形图。相邻的条形图元绘制在次y轴上,通常为百分比,在0和1之间绘制 我目前使用的解决方案能够很好地表示数据,但我很想知道如何实现堆叠条旁边的等宽单条的预期结果Python 如何创建部分堆叠的条形图,python,pandas,matplotlib,Python,Pandas,Matplotlib,我想做一个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 my
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('')
让我们尝试通过
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()
输出:
整洁!我打算使用position参数并传递position=1和position=0。@ScottBoston是的,
position
也很整洁。position对多个相邻条有效吗?(即一个堆叠,两个相邻)与边缘相同,不太可能工作。当一个刻度上有两个以上的条时,您需要手动移动条。我知道,手动移动条会将它们设置为新的x值,调整为与相邻条齐平?thx@QuangHoang