怎么在matplotlib中利用bar()函數(shù)實現(xiàn)一個百分比堆積柱狀圖-創(chuàng)新互聯(lián)

怎么在matplotlib中利用bar()函數(shù)實現(xiàn)一個百分比堆積柱狀圖?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

創(chuàng)新互聯(lián)建站長期為上千客戶提供的網(wǎng)站建設服務,團隊從業(yè)經(jīng)驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為樂昌企業(yè)提供專業(yè)的成都網(wǎng)站設計、成都網(wǎng)站制作、外貿(mào)網(wǎng)站建設,樂昌網(wǎng)站改版等技術服務。擁有十年豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。

適用于少量數(shù)據(jù),數(shù)據(jù)結(jié)構(gòu)需要手動構(gòu)造。


import matplotlib.pyplot as plt

labels = ['G1', 'G2', 'G3', 'G4', 'G5']
first = [20, 34, 30, 35, 27]
second = [25, 32, 34, 20, 25]
third = [21, 31, 37, 21, 28]
fourth = [26, 31, 35, 27, 21]
data = [first, second, third, fourth]

x = range(len(labels))
width = 0.35

# 將bottom_y元素都初始化為0
bottom_y = [0] * len(labels)
# 計算每組柱子的總和,為計算百分比做準備
sums = [sum(i) for i in zip(first, second, third, fourth)]
for i in data:
 # 計算每個柱子的高度,即百分比
 y = [a/b for a, b in zip(i, sums)]
 plt.bar(x, y, width, bottom=bottom_y)
 # 計算bottom參數(shù)的位置
 bottom_y = [(a+b) for a, b in zip(y, bottom_y)]

plt.xticks(x, labels)
plt.title('Percent stacked bar ')
plt.show()

使用numpy版本

第一個版本的缺陷在于數(shù)據(jù)需要手動構(gòu)造,而且計算稍微繁瑣一些。
使用numpy便于處理規(guī)模比較大且已存儲在文件中數(shù)據(jù)的數(shù)據(jù),計算更簡便。

import numpy as np
import matplotlib.pyplot as plt

labels = ['G1', 'G2', 'G3', 'G4', 'G5']
first = [20, 34, 30, 35, 27]
second = [25, 32, 34, 20, 25]
third = [21, 31, 37, 21, 28]
fourth = [26, 31, 35, 27, 21]
data = [first, second, third, fourth]

x = range(len(labels))
width = 0.35

# 將bottom_y元素都初始化為0
bottom_y = np.zeros(len(labels))
data = np.array(data)
# 按列計算計算每組柱子的總和,為計算百分比做準備
sums = np.sum(data, axis=0)
for i in data:
 # 計算每個柱子的高度,即百分比
 y = i / sums
 plt.bar(x, y, width, bottom=bottom_y)
 # 計算bottom參數(shù)的位置
 bottom_y = y + bottom_y

plt.xticks(x, labels)
plt.title('Percent stacked bar ')
plt.show()

關于怎么在matplotlib中利用bar()函數(shù)實現(xiàn)一個百分比堆積柱狀圖問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關知識。

網(wǎng)頁題目:怎么在matplotlib中利用bar()函數(shù)實現(xiàn)一個百分比堆積柱狀圖-創(chuàng)新互聯(lián)
地址分享:http://muchs.cn/article38/ceopsp.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、網(wǎng)站內(nèi)鏈、響應式網(wǎng)站自適應網(wǎng)站、網(wǎng)站制作Google

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設