1. 程式人生 > >Matplotlib學習---用seaborn畫直方圖和核密度圖(histogram & kdeplot)

Matplotlib學習---用seaborn畫直方圖和核密度圖(histogram & kdeplot)

tro ima 直方圖 subplot 平滑 style 創建 hist detail

由於直方圖受組距(bin size)影響很大,設置不同的組距可能會產生完全不同的可視化結果。因此我們可以用密度平滑估計來更好地反映數據的真實特征。具體可參見這篇文章:https://blog.csdn.net/unixtch/article/details/78556499

還是用我們自己創建的一組符合正態分布的數據來畫圖。

準備工作:先導入matplotlib,seaborn和numpy,然後創建一個圖像和一個坐標軸

import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
fig,ax=plt.subplots()

用seaborn畫核密度圖: sns.kdeplot(x,shade=True)

讓我們在用matplotlib畫好的直方圖的基礎上畫核密度圖:

import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
fig,ax=plt.subplots()

np.random.seed(4) #設置隨機數種子
Gaussian=np.random.normal(0,1,1000) #創建一組平均數為0,標準差為1,總個數為1000的符合標準正態分布的數據
ax.hist(Gaussian,bins=25,histtype="
stepfilled",normed=True,alpha=0.6) sns.kdeplot(Gaussian,shade=True) plt.show()

圖像如下:

技術分享圖片

註意:導入seaborn包後,繪圖風格自動變為seaborn風格。

另外,可以用distplot命令把直方圖和KDE一次性畫出來。

用seaborn畫直方圖和核密度圖: sns.distplot(x)

代碼如下:

import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
fig,ax=plt.subplots()

np.random.seed(
4) #設置隨機數種子 Gaussian=np.random.normal(0,1,1000) #創建一組平均數為0,標準差為1,總個數為1000的符合標準正態分布的數據 sns.distplot(Gaussian)

plt.show()

圖像和上面基本一致:

技術分享圖片

Matplotlib學習---用seaborn畫直方圖和核密度圖(histogram & kdeplot)