簡體   English   中英

Python和Matplotlib:使用Numpy.Array堆積條形圖

[英]Python & Matplotlib : Using Numpy.Array for Stacked Bar Graph

我正在嘗試使用堆積條形圖顯示包含我的數據的圖形。 我的數據是

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循環之類的功能)

因為您有類,所以我沒有測試過代碼,並且它並不是最少的工作片段。 但是,從上一個示例中可以看到,將索引增加了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會產生一點警告,它將對您的數組進行逐元素求和)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM