本文介紹seaborn.distplot繪製單變量分布圖(直方圖及核密度圖)。
本文內容概要1、seaborn.distplot
數據準備
繪製直方圖hist
修改直方圖hist中箱子數bins
直方圖成箱方式
繪製核密度曲線kernel density estimate (KDE)
seaborn.kdeplot繪製窄寬度核密度曲線
bandwidth (bw),控制核密度曲線胖瘦
核密度曲線結合直方圖
fit參數
seaborn.distplot簡介seaborn.distplot(a, bins=None, hist=True, kde=True, rug=False, fit=None, hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None, color=None, vertical=False, norm_hist=False, axlabel=None, label=None, ax=None)
matplotlib中的直方圖hist(默認繪製直方圖)數據準備
http://seaborn.pydata.org/generated/seaborn.distplot.html#seaborn.distplot
整合了如下三個函數:import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x=np.random.randn(100)#造一個shape為(100,),服從正態分布的對象x
print(x)
print(x.shape)繪製直方圖hist
plt.figure(dpi=120)
sns.set(style='dark')
sns.set_style("dark", {"axes.facecolor": "#e9f3ea"})#修改背景色
g=sns.distplot(x,
hist=True,#默認繪製直方圖,詳細參考plt.hist
kde=False,
color="#098154")#修改柱子顏色修改直方圖hist中箱子數bins
plt.figure(dpi=120)
sns.set(style='dark')
sns.set_style("dark", {"axes.facecolor": "#e9f3ea"})
g=sns.distplot(x,
hist=True,
bins=15,#修改箱子個數
kde=False,
color="#098154")
直方圖成箱方式有4種方式:'bar,barstacked,step,stepfilled'。
sns.set(style='dark')
sns.set_style("dark", {"axes.facecolor": "#e9f3ea"})
for i in list('bar,barstacked,step,stepfilled'.split(',')):
plt.figure(dpi=120)
sns.distplot(x,
hist=True,
bins=15,
kde=False,
hist_kws={'histtype':'%s'%i}, #默認為bar,可選barstacked,step,stepfilled
color="#098154")
plt.title("histtype="'%s'%i)
plt.show()繪製核密度曲線kernel density estimate (KDE)
plt.figure(dpi=120)
sns.set(style='dark')
sns.set_style("dark", {"axes.facecolor": "#e9f3ea"})
g=sns.distplot(x,
hist=False,
kde=True,#開啟核密度曲線kernel density estimate (KDE)
kde_kws={'linestyle':'--','linewidth':'1','color':'#098154',#設置外框線屬性
'shade':True,#開啟填充
},
)seaborn.kdeplot繪製窄寬度核密度曲線
plt.figure(dpi=120)
sns.set(style='dark')
sns.set_style("dark", {"axes.facecolor": "#e9f3ea"})#修改背景色
g=sns.kdeplot(x,
shade=True,
bw=0.15,#使用窄帶寬
color="#098154"
)bandwidth (bw),控制核密度曲線胖瘦
類似hist中bin size
plt.figure(dpi=120)
sns.set(style='dark')
sns.set_style("dark", {"axes.facecolor": "#e9f3ea"})
sns.kdeplot(x,shade=True, label="bw: defult")
sns.kdeplot(x, bw=.2, label="bw: 0.2")
sns.kdeplot(x, bw=2, label="bw: 2")
plt.legend();核密度曲線結合直方圖
plt.figure(dpi=120)
sns.set(style='dark')
sns.set_style("dark", {"axes.facecolor": "#e9f3ea"})
g=sns.distplot(x,
hist=True,
kde=True,#開啟核密度曲線kernel density estimate (KDE)
kde_kws={'linestyle':'--','linewidth':'1','color':'#c72e29',#設置外框線屬性
},
color='#098154',
axlabel='Xlabel',#設置x軸標題
)fit參數
將數據與scipy.stats中的分布擬合,查看數據服從何種分布,更多可參考:https://docs.scipy.org/doc/scipy/reference/stats.html
from scipy.stats import norm#導入正態分布
plt.figure(dpi=120)
sns.set(style='dark')
sns.set_style("dark", {"axes.facecolor": "#e9f3ea"})
g=sns.distplot(x,
hist=True,
kde=False,
kde_kws={'linestyle':'--','linewidth':'1','color':'#c72e29',
},
fit=norm,#
color='#098154',參考資料:http://seaborn.pydata.org/generated/seaborn.distplot.html#seaborn.distplot