Python:广义Pyplot堆叠条形图

2024-04-18 00:39:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将matplotlib.org上给出的一个堆积条形图的例子加以推广。在

labels = ('G1','G2','G3','G4','G5');
values = [(20,35,30,35,27),(25,32,34,20,25),(3,4,5,6,7)];

for i in range(len(values)):
    if i == 0:
        plt.bar(np.arange(len(labels)),values[i],1);
    else:
        plt.bar(np.arange(len(labels)),values[i],1,bottom=values[i-1]);

plt.xticks(np.arange(len(labels))+0.5,labels);

但现在我发现了一个问题,那就是这些条线似乎没有正确堆叠:

如果要运行代码,import numpy as npimport matplotlib.pyplot as plt和{}。在

如果你喜欢,你也可以建议如何得到不同的颜色为每个酒吧。在


Tags: orgimportlabelslenmatplotlibasnpbar
2条回答

bottom的使用存在误解。工作代码现在是:

for i in range(len(values)):
    plt.bar(np.arange(len(labels)),values[i],1,bottom=[sum([values[j][pos] for j in range(i)]) for pos in range(len(labels))]);
plt.xticks(np.arange(len(labels))+0.5,labels);

为了便于打印,我现在将使用kwarg颜色:

^{pr2}$

像这样:

import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle
from six.moves import zip

def stack_bar(ax, list_of_vals, color_cyle=None, **kwargs):
    """
    Generalized stacked bar graph.

    kwargs are passed through to the call to `bar`

    Parameters
         
    ax : matplotlib.axes.Axes
       The axes to plot to

    list_of_vals : iterable
       An iterable of values to plot

    color_cycle : iterable, optional
       color_cycle is None, defaults
       to `cycle(['r', 'g', 'b', 'k'])`


    """
    if color_cyle is None:
        color_cyle = cycle(['r', 'g', 'b', 'k'])
    else:
        color_cycle = cycle(color_cycle)


    v0 = len(list_of_vals[0])
    if any(v0 != len(v) for v in list_of_vals[1:]):
           raise ValueError("All inputs must be the same length")

    edges = np.arange(v0)
    bottom = np.zeros(v0)
    for v, c in zip(list_of_vals, color_cyle):
        ax.bar(edges, v, bottom=bottom, color=c, **kwargs)
        bottom += np.asarray(v)


fig, ax = plt.subplots(1, 1)
values = [(20,35,30,35,27),(25,32,34,20,25),(3,4,5,6,7)]
stack_bar(ax, values, width=1)

它需要一些提示和错误检查

也作为gist

相关问题 更多 >

    热门问题