matplotlib bar()實(shí)現(xiàn)百分比堆積柱狀圖
使用matplotlib
創(chuàng)建百分比堆積柱狀圖的思路與堆積柱狀圖類(lèi)似,只不過(guò)bottom
參數(shù)累計(jì)的不是數(shù)值而是百分比,因此,需要事先計(jì)算每組柱子的數(shù)值總和,進(jìn)而求百分比。
未使用numpy版本
適用于少量數(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()
使用numpy版本
第一個(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)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Python中映射類(lèi)型(字典)操作符的概念和使用
這篇文章主要介紹了詳解Python中映射類(lèi)型(字典)操作符的概念和使用,字典是目前Python中唯一的映射類(lèi)型,需要的朋友可以參考下2015-08-08Python依賴(lài)管理及打包工具Poetry使用規(guī)范
這篇文章主要為大家介紹了Python依賴(lài)管理及打包工具Poetry的依賴(lài)規(guī)范,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-09-09python 獲取一個(gè)值在某個(gè)區(qū)間的指定倍數(shù)的值方法
今天小編就為大家分享一篇python 獲取一個(gè)值在某個(gè)區(qū)間的指定倍數(shù)的值方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11

Python安裝Gradio和常見(jiàn)安裝問(wèn)題解決辦法

關(guān)于DataFrame取值操作總結(jié)(取指定列指定值的行)

Python數(shù)據(jù)類(lèi)型詳解(四)字典:dict

淺談python多進(jìn)程共享變量Value的使用tips