Python繪制堆疊柱狀圖的實例
有個朋友要求幫忙繪制堆疊柱狀圖,查閱了一些文檔之后也算是完成了,只是一個小demo,下面我就記錄一下。
1.什么是堆疊柱狀圖
與并排顯示分類的分組柱狀圖不同,堆疊柱狀圖將每個柱子進行分割以顯示相同類型下各個數(shù)據(jù)的大小情況。它可以形象的展示一個大分類包含的每個小分類的數(shù)據(jù),以及各個小分類的占比,顯示的是單個項目與整體之間的關(guān)系。效果圖如下:
2.數(shù)據(jù)展示
這里展示了部分數(shù)據(jù),主要是treatment就是對應(yīng)的上圖分類一,分類二;species就是對應(yīng)的分組;ra就是對應(yīng)的各個分組的比例。
3.Python代碼
from matplotlib import pyplot as plt import pandas as pd import xlrd import numpy as np data = xlrd.open_workbook('ccc.xlsx') #打開數(shù)據(jù) table = data.sheet_by_index(0) #獲取sheet1的數(shù)據(jù) nrows = table.nrows #獲取sheet1中的行 plot_list = ['plot1'] plot1_ra_list = [[0] for i in range(17)]#構(gòu)建一個17X1的列表 i = 0 for row in range(1,nrows): #循環(huán)讀取表內(nèi)數(shù)據(jù) if table.cell(row,0).value == 2015.0 and table.cell(row,1).value == 'plot1': print(table.cell(row, 3).value) #第三列是各個元素所占的比例 print(i) plot1_ra_list[i][0]=(float(table.cell(row, 3).value)) i+=1 #顏色列表 color = ['y','r','snow','b','k','g','orange','c','bisque','brown','lime','aqua','coral','darkcyan','gold','teal','pink',] plt.figure(figsize=(8,6)) for i in range(17): plt.bar(range(len(plot1_ra_list[i])), plot1_ra_list[i],bottom=np.sum(plot1_ra_list[:i],axis = 0),label=str(i+1),tick_label = plot_list,fc = color[i]) plt.legend() plt.show()
4.效果展示
上述代碼我只做了2015年的plot1,如果要把plot2增加上注意要對齊plot1和plot2的species數(shù)量,可以認為的添加,并補充對應(yīng)的ra為0,這樣子也不影響整個做圖。下面我PO一張demo。
以上這篇Python繪制堆疊柱狀圖的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python中dtype、type()和astype()的區(qū)別詳解
這篇文章主要介紹了Python中dtype、type()和astype()的區(qū)別詳解,type()是python內(nèi)置的函數(shù),type()返回數(shù)據(jù)結(jié)構(gòu)類型(list、dict、numpy.ndarray 等),需要的朋友可以參考下2023-08-08TensorFlow和Numpy矩陣操作中axis理解及axis=-1的解釋
在調(diào)用numpy庫中的concatenate()時,有遇到axis=-1/1/0的情況,下面這篇文章主要給大家介紹了關(guān)于TensorFlow和Numpy矩陣操作中axis理解及axis=-1解釋的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-03-03