首页 > 解决方案 > Python 和 Matplotlib:使用 Numpy.Array 制作堆积条形图

问题描述

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

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

如果我在上面使用此代码;显示此图表。如您所见;紫色区域在某处的蓝色区域中。总数(如您在左侧看到的)是错误的。

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

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

显示此图表,这就是我想要完美显示颜色和总数的图表。但我认为这个解决方案太原始了。因为,有时new_total会有 5 或 7 个元素。你能用完美的方式修复我的解决方案吗(它可以有 for 循环或其他)

标签: pythonarrayspython-3.xnumpymatplotlib

解决方案


因为你有课程,所以我没有测试过代码,而且它不是最小的工作片段。但是,正如您从上一个示例中看到的那样,您将索引增加 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将按元素对数组求和)。


推荐阅读