使用matplotlib
創(chuàng)建百分比堆積柱狀圖的思路與堆積柱狀圖類似,只不過(guò)bottom
參數(shù)累計(jì)的不是數(shù)值而是百分比,因此,需要事先計(jì)算每組柱子的數(shù)值總和,進(jìn)而求百分比。
適用于少量數(shù)據(jù),數(shù)據(jù)結(jié)構(gòu)需要手動(dòng)構(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) # 計(jì)算每組柱子的總和,為計(jì)算百分比做準(zhǔn)備 sums = [sum(i) for i in zip(first, second, third, fourth)] for i in data: # 計(jì)算每個(gè)柱子的高度,即百分比 y = [a/b for a, b in zip(i, sums)] plt.bar(x, y, width, bottom=bottom_y) # 計(jì)算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()
第一個(gè)版本的缺陷在于數(shù)據(jù)需要手動(dòng)構(gòu)造,而且計(jì)算稍微繁瑣一些。
使用numpy便于處理規(guī)模比較大且已存儲(chǔ)在文件中數(shù)據(jù)的數(shù)據(jù),計(jì)算更簡(jiǎn)便。
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) # 按列計(jì)算計(jì)算每組柱子的總和,為計(jì)算百分比做準(zhǔn)備 sums = np.sum(data, axis=0) for i in data: # 計(jì)算每個(gè)柱子的高度,即百分比 y = i / sums plt.bar(x, y, width, bottom=bottom_y) # 計(jì)算bottom參數(shù)的位置 bottom_y = y + bottom_y plt.xticks(x, labels) plt.title('Percent stacked bar ') plt.show()
到此這篇關(guān)于matplotlib bar()實(shí)現(xiàn)百分比堆積柱狀圖 的文章就介紹到這了,更多相關(guān)matplotlib 百分比堆積柱狀圖 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:海南 平頂山 郴州 合肥 哈爾濱 烏蘭察布 大慶 烏蘭察布
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《matplotlib bar()實(shí)現(xiàn)百分比堆積柱狀圖》,本文關(guān)鍵詞 matplotlib,bar,實(shí)現(xiàn),百分比,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。