在同一图中绘制多个堆叠的条形图

发布于 2021-01-29 16:12:31

我想在同一情节中多个堆叠的酒吧。这是我的代码:

    file_to_plot = file_to_plot.set_index(['user'])
    fig, ax = plt.subplots()
    fontP = FontProperties()
    fontP.set_size('small')
    file_to_plot[[" mean_accuracy_all_classes_normal", " delta_all_classes"]].plot(ax=ax, kind='bar', color= ['g', 'r'], width = 0.65, align="center", stacked=True)
    file_to_plot[[" mean_accuracy_user_classes_normal", " delta_user_classes"]].plot(ax=ax, kind='bar', color=['y', 'b'], width=0.65, align="center", stacked = True)
    lgd = ax.legend(['Tutte le classi (normale)', 'Tutte le classi (incrementale)', 'Classi utente (normale)', 'Classi utente (incrementale)'], prop=fontP, loc=9, bbox_to_anchor=(0.5, -0.15), ncol=4,borderaxespad=0.)
    ax.set_ylabel('% Accuratezza')
    ax.set_xlabel('Utenti')

结果如下:

在此处输入图片说明
当我想将它们绘制在一起时,第二个图使我不知所措。我能怎么做?

关注者
0
被浏览
138
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这应该按照您想要的方式工作:

    import pandas as pd
    
    df = pd.DataFrame(dict(
        A=[1, 2, 3, 4],
        B=[2, 3, 4, 5],
        C=[3, 4, 5, 6],
        D=[4, 5, 6, 7]))
    
    import matplotlib.pyplot as plt
    %matplotlib inline
    fig = plt.figure(figsize=(20, 10))
    
    ab_bar_list = [plt.bar([0, 1, 2, 3], df.B, align='edge', width= 0.2),
                   plt.bar([0, 1, 2, 3], df.A, align='edge', width= 0.2)]
    
    cd_bar_list = [plt.bar([0, 1, 2, 3], df.D, align='edge',width= -0.2),
                   plt.bar([0, 1, 2, 3], df.C, align='edge',width= -0.2)]
    

    在此处输入图片说明

    请记住,width一组的价值必须为正,第二组的价值为负。使用alignedge为好。
    你必须把与最大值酒吧的最低值,前杠,如果你想在酒吧中的另一条战线,变化出现堆积在彼此之上,而不是一个df.B,并df.Ddf.B + df.Adf.D + df.C,分别。如果没有明显或组成的模式,请使用alignbyedgewidthmethod以及@piRSquared建议的模式。
    另一种选择是访问绿色栏中的每个值,并将其与红色栏中的相应值进行比较,并进行相应的绘制(此操作中不必要的工作太多)。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看