以相同的指定顺序制作 pandas.plot 图例和堆栈

时间:2021-05-14 00:48:33

标签: pandas matplotlib

我有一个堆叠条形图,我想以指定的相同顺序显示图例和堆叠。

为了对图例类进行排序,我在 1, 2(我要排序的类)前面添加了 True, False。不是最理想的方式,但它有效。问题是,它不会对堆栈进行排序。

示例数据

d = {'sel_date':['2020-01', '2020-01', '2020-01', '2021-02', '2021-03', '2020-01', '2020-01', '2020-01', '2021-02', '2021-03'], \
     'id':list('yyzzz'*2), \
     'is_new': ['1. True', '1. True', '2. False', '1. True', '2. False', '1. True', '1. True', '2. False', '2. False', '2. False'], \
     'Short Name':list('ababa'*2)}
d
df = pd.DataFrame(data=d)
df
    sel_date    id  is_new  Short Name
0   2020-01     y   1. True     a
1   2020-01     y   1. True     b
2   2020-01     z   2. False    a
3   2021-02     z   1. True     b
4   2021-03     z   2. False    a
5   2020-01     y   1. True     a
6   2020-01     y   1. True     b
7   2020-01     z   2. False    a
8   2021-02     z   2. False    b
9   2021-03     z   2. False    a

用这个函数绘图

def plot_stacked_barplot_example(feature, suptitle=None, df=reg, groupby_column='Short Name'):
    sns.set_theme(style='white', font_scale=1.4)
    fig, ax = plt.subplots(figsize=(30, 20))
    for i, (group, data) in enumerate(df.groupby(groupby_column)):
        ax = plt.subplot(2, 2, i+1)   
        pivot = (data.groupby('sel_date')[feature].value_counts(normalize=True)
                    .mul(100).unstack(feature)
                    .plot(kind='bar', stacked=True, ax=ax
                ))
        ax.yaxis.set_major_formatter(mtick.PercentFormatter())
        ax.xaxis.set_ticks([])  # Hide labels from xticks
        ax.get_legend().remove()

    handles, labels = ax.get_legend_handles_labels()
    # sort both labels and handles by labels
    labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
    ax.legend(handles, labels, bbox_to_anchor=(1, 1), loc='upper left')
plot_stacked_barplot_example(df=df, feature='is_new')

enter image description here

我希望堆栈的顺序与图例相同。

0 个答案:

没有答案