
直方圖
直方圖(英語:Histogram)是一種對數(shù)據(jù)分布情況的圖形表示,是一種二維統(tǒng)計(jì)圖表,它的兩個(gè)坐標(biāo)分別是統(tǒng)計(jì)樣本和該樣本對應(yīng)的某個(gè)屬性的度量,一般以長條圖(bar)的形式具體表現(xiàn)。因?yàn)橹狈綀D的長度及寬度很適合用來表現(xiàn)數(shù)量上的變化,所以較容易解讀差異小的數(shù)值.
hist
- 函數(shù)定義:
在向量 x 和 y 指定的位置創(chuàng)建一個(gè)包含圓形的散點(diǎn)圖,該類型的圖形也稱為氣泡圖。
matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, \*, data=None, \*\*kwargs)[source]
- 常用參數(shù):
- x:
數(shù)據(jù)集,最終的直方圖將對數(shù)據(jù)集進(jìn)行統(tǒng)計(jì) - bins:
統(tǒng)計(jì)的區(qū)間分布劃分,指定bin(箱子)的個(gè)數(shù); - range:
顯示的區(qū)間,range在沒有給出bins時(shí)生效 - density:
顯示概率密度,默認(rèn)為false - 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:
默認(rèn)為False,y坐標(biāo)軸是否選擇指數(shù)刻度,在數(shù)據(jù)分布的范圍較大的時(shí)候,可以通過log指數(shù)刻度來縮小顯示的范圍。 - stacked:
默認(rèn)為False,是否為堆積狀圖
hist的詳細(xì)定義:
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html?highlight=hist#matplotlib.pyplot.hist
示例說明:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
"""
font:設(shè)置中文
unicode_minus:顯示負(fù)好
"""
matplotlib.rcParams['font.family'] = ['Heiti TC']
matplotlib.rcParams['axes.unicode_minus']=False # 正常顯示負(fù)號
"""
隨機(jī)數(shù)生成,自動生成正態(tài)分布的數(shù)據(jù)集
"""
data = np.random.randn(10000)
"""
facecolor:長條形的顏色
edgecolor:長條形邊框的顏色
alpha:透明度
"""
plt.hist(data, bins=40, density=False, facecolor="tab:blue", edgecolor="tab:orange", alpha=0.7)
"""
xlabel:橫軸標(biāo)簽
ylabel:縱軸標(biāo)簽
title:圖標(biāo)題
"""
plt.xlabel("區(qū)間")
plt.ylabel("頻數(shù)(頻數(shù))")
plt.title("頻數(shù)(頻率)分布圖")
plt.show()

擴(kuò)展應(yīng)用:
- 增加不同長條形色彩映射
利用hist函數(shù)的三個(gè)返回值,對每一個(gè)不同區(qū)間進(jìn)行不同顏色的顯示.通過這種方式可以直觀的看出分布的差異.
n: 數(shù)組或數(shù)組列表,表明每一個(gè)bar區(qū)間的數(shù)量或者百分比;
bins : 數(shù)組,bar的范圍和bins參數(shù)含義一樣;
patches : 列表,每個(gè)bar圖形對象;
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
"""
font:設(shè)置中文
unicode_minus:顯示負(fù)好
"""
matplotlib.rcParams['font.family'] = ['Heiti TC']
matplotlib.rcParams['axes.unicode_minus']=False # 正常顯示負(fù)號
"""
隨機(jī)數(shù)生成,自動生成正態(tài)分布的數(shù)據(jù)集
"""
data = np.random.randn(10000)
"""
n: 數(shù)組或數(shù)組列表,表明每一個(gè)bar區(qū)間的數(shù)量或者百分比
bins : 數(shù)組,bar的范圍和bins參數(shù)含義一樣
patches : 列表 或者列表的列表 圖形對象
"""
n, bins, patches =plt.hist(data, bins=40,)
percent = n / n.max()
#將percent中的數(shù)據(jù)進(jìn)行正則化,這樣可以方便的映射到colormap中
norm = colors.Normalize(percent.min(), percent.max())
"""
patches為對應(yīng)每個(gè)長條的對象,循環(huán)為每個(gè)bar條進(jìn)行顏色的設(shè)置.
set_facecolor()用來設(shè)置條形的顏色
"""
for thisfrac, thispatch in zip(percent, patches):
color = plt.cm.viridis(norm(thisfrac))
thispatch.set_facecolor(color)
"""
xlabel:橫軸標(biāo)簽
ylabel:縱軸標(biāo)簽
title:圖標(biāo)題
"""
plt.xlabel("區(qū)間")
plt.ylabel("頻數(shù)(頻數(shù))")
plt.title("頻數(shù)(頻率)分布圖")
plt.show()

- 顯示多個(gè)數(shù)據(jù)的直方圖
可以在一個(gè)圖中顯示多個(gè)數(shù)據(jù)的直方圖,方便對不同數(shù)據(jù)進(jìn)行對比.
重點(diǎn)區(qū)分坐標(biāo)系一和坐標(biāo)系四兩者之間顯示的區(qū)別
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(64)
n_bins = 20
"""
生成為一個(gè)緯度為(6000,3)的隨機(jī)數(shù)據(jù)
"""
x = np.random.randn(6000, 3)
"""
生成有兩行行列坐標(biāo)系的畫布
"""
fig, axes = plt.subplots(nrows=2, ncols=2,figsize=(16,9))
"""
第一坐標(biāo)系,使用bar條來顯示
為了和第四坐標(biāo)系進(jìn)行效果對比,次數(shù)對三列隨機(jī)數(shù)進(jìn)行分別顯示
"""
colors = ['tab:blue', 'tab:orange', 'tab:green']
alpha=[1,0.6,0.3]
for index in np.arange(x.shape[1]):
axes[0][0].hist(x[:,index], n_bins, density=True, histtype='bar', color=colors[index], label=colors[index],alpha=alpha[index])
#axes[0][0].hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors)
axes[0][0].legend(prop={'size': 10})
axes[0][0].set_title('bar hist')
"""
第二坐標(biāo)系,使用bar條來顯示,設(shè)置的堆積的屬性stacked
"""
axes[0][1].hist(x, n_bins, density=True, histtype='bar', stacked=True)
axes[0][1].set_title('stacked bar hist')
"""
第三坐標(biāo)系,使用step來顯示,設(shè)置的堆積的屬性stacked
"""
axes[1][0].hist(x, n_bins, histtype='step', stacked=True, fill=False)
axes[1][0].set_title('stacked step hist')
"""
第四坐標(biāo)系,一次性顯示三列數(shù)據(jù)
"""
axes[1][1].hist(x, n_bins, density=True,histtype='bar')
axes[1][1].set_title('bat hist')
fig.tight_layout()
plt.show()

- 雙變量直方圖
在進(jìn)行一維頻次直方圖繪制之外,可以對二維數(shù)組按照二維區(qū)間進(jìn)行二維頻次的直方圖繪制.
重點(diǎn):此處使用另外一種方式進(jìn)行多子圖的繪制,利用GridSpec可以更加靈活的多子圖的繪制
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from matplotlib.ticker import PercentFormatter
import matplotlib.gridspec as gridspec
np.random.seed(64)
N_points = 800
n_bins = 40
"""
生成為x,y隨機(jī)數(shù)據(jù)
"""
x = np.random.randn(N_points)
y = 2* x + np.random.randn(N_points) + 5
fig = plt.figure(figsize=(10, 8))
# gridspec的用法,可以使圖像橫跨多個(gè)坐標(biāo)
G = gridspec.GridSpec(2, 2)
#顯示第一坐標(biāo)系,其位置第一行,第一列(G[0, 0])
axes =fig.add_subplot(G[0, 0])
axes.hist(x, bins=n_bins)
#顯示第二坐標(biāo)系,其位置第一行,第二列(G[0, 1])
axes =fig.add_subplot(G[0, 1])
axes.hist(y, bins=n_bins)
#顯示第三坐標(biāo)系,其位置第二行整行(G[1, :])
axes =fig.add_subplot(G[1, :])
axes.hist2d(x,y, bins=n_bins)
plt.show()
