本文實例講述了Python基于matplotlib繪制棧式直方圖的方法。分享給大家供大家參考,具體如下:
平時我們只對一組數(shù)據(jù)做直方圖統(tǒng)計,這樣我們只要直接畫直方圖就可以了。
但有時候我們同時畫多組數(shù)據(jù)的直方圖(比如說我大一到大四跑大學(xué)城內(nèi)環(huán)的用時的分布),大一到大四用不同顏色的直方圖,顯示在一張圖上,這樣會很直觀。
#!/usr/bin/env python# -*- coding: utf-8 -*-#//www.jb51.net/article/100363.htm# numpy array intorduction#http://matplotlib.org/examples/statistics/histogram_demo_multihist.htmlimport numpy as npimport pylab as Pimport matplotlibd1=np.array([18.46,19.15,18.13 ,18.30 ,18.07 ,18.24 ,18.26 , 17.14 ,18.44 ,18.06 ,17.44 ,16.57 ,16.34 ,17.21 ])d1=d1//1+(d1-d1//1)/0.6d2=np.array([19.33 ,19.06 ,18.10 ,17.55 ,19.55 ,19.13 ,18.54 , 18.30 ,18.36 ,19.59 ,20.01 ,19.17 ,19.30 ,18.54 ,18.35 ,20.04 ])d2=d2//1+(d2-d2//1)/0.6d3=np.array([20.52 ,20.41 ,19.20 ,19.04 ,19.09 ,19.01 ,17.49 ,19.18 ,20.01 ,20.11 ])d3=d3//1+(d3-d3//1)/0.6d4=np.array([22.02 ,21.03,21.06 ,20.46 ,19.46 ,20.15 ,19.49 ,19.43 , 19.51 ,19.39 ,19.33 ,19.18 ,19.13 ,19.22 ,18.46 ,19.07 , 18.57 ,18.45 ,19.17 ,18.41 ,18.30 ])d4=d4//1+(d4-d4//1)/0.6x=([d1,d2,d3,d4])P.figure()#normed is False is goodn, bins, patches = P.hist(x, 12, [16.5, 22.5],normed=0, histtype='barstacked', color=['blue', 'green', 'red','yellow'], label=[' ', ' ', ' ',' '])print type(x)P.legend()#legend should be signed after set down the informationP.show()

以上圖為例,很明顯看到藍(lán)色直方圖(大一)跑得最快,黃色(大四)直方圖跑得最慢。
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
新聞熱點(diǎn)
疑難解答