【问题标题】:How to Create Partially Stacked Bar Plot如何创建部分堆积条形图
【发布时间】:2020-10-22 01:36:37
【问题描述】:

我想制作一个 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('')

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    让我们尝试通过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 也很整洁。
    • 位置是否适用于多个相邻栏? (即一个堆叠和两个相邻)
    • 与 edge 一样,不太可能工作。当一个刻度有两个以上的柱时,您需要手动移动柱。
    • 我明白了,手动移动条形图会将它们设置为调整为与相邻条形图齐平的新 x 值?谢谢@QuangHoang