直方圖與柱狀圖外觀表現(xiàn)很相似,用來展現(xiàn)連續(xù)型數(shù)據(jù)分布特征的統(tǒng)計圖形(柱狀圖主要展現(xiàn)離散型數(shù)據(jù)分布),官方hist項目地址。
函數(shù):matplotlib.pyplot.hist(x,bins=None,range=None, density=None, bottom=None, histtype='bar', align='mid', log=False, color=None, label=None, stacked=False, normed=None)
關(guān)鍵參數(shù)
x: 數(shù)據(jù)集,最終的直方圖將對數(shù)據(jù)集進(jìn)行統(tǒng)計
bins: 統(tǒng)計的區(qū)間分布
range: tuple, 顯示的區(qū)間,range在沒有給出bins時生效
density: bool,默認(rèn)為false,顯示的是頻數(shù)統(tǒng)計結(jié)果,為True則顯示頻率統(tǒng)計結(jié)果,這里需要注意,頻率統(tǒng)計結(jié)果=區(qū)間數(shù)目/(總數(shù)*區(qū)間寬度),和normed效果一致,官方推薦使用density
histtype: 可選{'bar', 'barstacked', 'step', 'stepfilled'}之一,默認(rèn)為bar,推薦使用默認(rèn)配置,step使用的是梯狀,stepfilled則會對梯狀內(nèi)部進(jìn)行填充,效果與bar類似
align: 可選{'left', 'mid', 'right'}之一,默認(rèn)為'mid',控制柱狀圖的水平分布,left或者right,會有部分空白區(qū)域,推薦使用默認(rèn)
log: bool,默認(rèn)False,即y坐標(biāo)軸是否選擇指數(shù)刻度
stacked: bool,默認(rèn)為False,是否為堆積狀圖
最簡實現(xiàn)
import matplotlib.pyplot as plt
import numpy as np
x=np.random.randint(0,100,100)#生成【0-100】之間的100個數(shù)據(jù),即 數(shù)據(jù)集
bins=np.arange(0,101,10)#設(shè)置連續(xù)的邊界值,即直方圖的分布區(qū)間[0,10],[10,20]...
#直方圖會進(jìn)行統(tǒng)計各個區(qū)間的數(shù)值
plt.hist(x,bins,color='fuchsia',alpha=0.5)#alpha設(shè)置透明度,0為完全透明
plt.xlabel('scores')
plt.ylabel('count')
plt.xlim(0,100)#設(shè)置x軸分布范圍
plt.show()
效果圖:


import matplotlib.pyplot as plt
import numpy as np
x=np.random.randint(0,100,100)#生成【0-100】之間的100個數(shù)據(jù),即 數(shù)據(jù)集
bins=np.arange(0,101,10)#設(shè)置連續(xù)的邊界值,即直方圖的分布區(qū)間[0,10],[10,20]...
width=10#柱狀圖的寬度
#直方圖會進(jìn)行統(tǒng)計各個區(qū)間的數(shù)值
frequency_each,_,_= plt.hist(x,bins,color='deepskyblue',width=width,alpha=0.7)#alpha設(shè)置透明度,0為完全透明
plt.xlabel('scores')
plt.ylabel('count')
plt.xlim(0,100)#設(shè)置x軸分布范圍
plt.plot(bins[1:]-(width//2),frequency_each,color='palevioletred')#利用返回值來繪制區(qū)間中點連線
plt.show()
處理效果:
