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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47205918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:45:13  来源:igfitidea点击:

Plot multiple stacked bar in the same figure

pythonpandasmatplotlib

提问by sigLosco

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

This is the results:

这是结果:

enter image description hereThe second plot overwhelms me when I want to plot them together. How can I do?

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

回答by Meher Béjaoui

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

enter image description here

在此处输入图片说明

Just keep in mind, the widthvalue for one group must be positive, and negative for the second one. Use alignby edgeas 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.Band df.Dto df.B + df.Aand df.D + df.C, respectively. If there's no apparent or consisting pattern, use the alignby edgeand widthmethod 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).

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

回答by piRSquared

I thought this would be straightforward. Hopefully someone else will chime in with a better solution. What I did was to take the diff's of the columns and run a stacked chart.

我认为这很简单。希望其他人会提出更好的解决方案。我所做的是获取列的差异并运行堆积图。

df = pd.DataFrame(dict(
    A=[1, 2, 3, 4],
    B=[2, 3, 4, 5],
    C=[3, 4, 5, 6]
))

df.diff(axis=1).fillna(df).astype(df.dtypes).plot.bar(stacked=True)

enter image description here

在此处输入图片说明



For comparison

比较

fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)

df.plot.bar(ax=axes[0])
df.diff(axis=1).fillna(df).astype(df.dtypes).plot.bar(ax=axes[1], stacked=True)

enter image description here

在此处输入图片说明