在同一图中绘制多个堆叠的条形图 [英] Plot multiple stacked bar in the same figure

查看:84
本文介绍了在同一图中绘制多个堆叠的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在同一个图中有多个堆叠的条形图.这是我的代码:

i would like to multiple stacked bar in the same plot. This is my code:

    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')

这是结果:

当我想将它们一起绘制时,第二个情节让我不知所措.我该怎么办?

The second plot overwhelms me when I want to plot them together. How can I do?

推荐答案

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

This should work the way you want:

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 值必须为正,第二组的值必须为负.还要通过 edge 使用 align .
您必须将具有最大值的条形放置在具有最小值的条形放置之前,并且如果要使这些条形显示为彼此堆叠而不是在另一条堆叠之前,请更改 df.B df.Ddf.B + df.Adf.D + df.C ,分别.如果没有明显或组成的模式,请使用 align by edgewidth 方法以及@piRSquared 建议的方法.
另一种替代方法是访问绿色条中的每个值,并将其与红色条中的相应值进行比较,然后相应地进行绘图(在此过程中有太多不必要的工作).

Just keep in mind, the width value for one group must be positive, and negative for the second one. Use align by edge as well.
You have to place the bar with the biggest values before the bar with the lowest values, and if you want the bars to appear stacked above one another rather than one in front of another, change df.B and df.D to df.B + df.A and df.D + df.C, respectively. If there's no apparent or consisting pattern, use the align by edge and width method with the one suggested by @piRSquared.
Another alternative would be to access each value from a green bar and compare it to the corresponding value from the red bar, and plot accordingly (too much unnecessary work in this one).

这篇关于在同一图中绘制多个堆叠的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆