Python和Matplotlib:使用Numpy.Array堆积条形图

时间:2019-04-10 14:13:05

标签: python arrays python-3.x numpy matplotlib

我正在尝试使用堆积条形图显示包含我的数据的图形。我的数据是;

new_total = [[5,3,11,17,2,1,5,38,30,45,15,0],[8,21,13,54,21,7,20,103,114,149,77,15],[0,2,6,7,2,6,2,6,22,0,3,0],[0,9,3,11,10,0,0,26,47,17,7,9],[0,11,4,2,5,1,10,35,35,19,16,0],[0,0,0,2,0,0,2,5,6,16,4,3]]

它有6个元素,每个元素代表一种颜色(每个元素有12个子元素)。用我的代码和图片解释;

width = 0.5
ind = np.arange(N)  # the x locations for the groups
temp = []
myMax = 0
myCount = 0
for x in range(len(movies)):
    myCount = myCount + 1
    if myCount == 1:
        self.axes.bar(ind, new_total[0], width)
        temp = np.zeros(N)
    else:
        if x == len(movies) - 1:
            myMax = max(np.add(temp, new_total[x - 1]))
        self.axes.bar(ind, new_total[x], width, bottom=np.add(temp, new_total[x - 1]))

如果我在上面使用此代码;显示this graph。如您所见;紫色区域在某处的蓝色区域。而且总数(如左图所示)是错误的。

但是如果我在下面使用此代码;

self.axes.bar(ind, new_total[0], width)
self.axes.bar(ind, new_total[1], width, bottom=np.array(new_total[0]))
self.axes.bar(ind, new_total[2], width, bottom=np.add(new_total[0],new_total[1])) #I could use np.array(new_total[0]) + np.array(new_total[1])
self.axes.bar(ind, new_total[3], width, bottom=np.array(new_total[0]) + np.array(new_total[1]) + np.array(new_total[2]))
self.axes.bar(ind, new_total[4], width, bottom=np.array(new_total[0]) + np.array(new_total[1]) + np.array(new_total[2]) + np.array(new_total[3]))
self.axes.bar(ind, new_total[5], width, bottom=np.array(new_total[0]) + np.array(new_total[1]) + np.array(new_total[2]) + np.array(new_total[3]) + np.array(new_total[4]))

This graph显示出来,这就是我想要的图形,它完美地显示了颜色和总数。但是我认为这种解决方案太原始了。因为有时new_total会包含5或7个元素。您能以一种完美的方式解决我的解决方案吗(它可以具有for循环之类的功能)

1 个答案:

答案 0 :(得分:1)

由于您有类,因此我还没有测试过代码,并且它并不是最少的工作片段。但是,从上一个示例中可以看到,索引增加了1(对于for loop来说似乎很棒)。然后您会看到bottom始终是所有先前元素的总和,这同样适用于for循环,但是在这里使用分片表示法很方便。因此,鉴于此,代码应如下所示:

for i, sublist in enumerate(new_total):
    self.axes.bar(ind, sublist, bottom=np.sum(new_total[0:i], axis=0), width=width)

使用np.sum()函数与axis=0,这将对您的数组进行逐元素求和。)