Python?seaborn數(shù)據(jù)可視化繪圖(直方圖,密度圖,散點(diǎn)圖)
前言
系統(tǒng)自帶的數(shù)據(jù)表格,使用時(shí)通過(guò)sns.load_dataset('表名稱')即可,結(jié)果為一個(gè)DataFrame。
print(sns.get_dataset_names()) #獲取所有數(shù)據(jù)表名稱 # ['anscombe', 'attention', 'brain_networks', 'car_crashes', 'diamonds', 'dots', 'exercise', 'flights', # 'fmri', 'gammas', 'iris', 'mpg', 'planets', 'tips', 'titanic'] tips = sns.load_dataset('tips') #導(dǎo)入小費(fèi)tips數(shù)據(jù)表,返回一個(gè)DataFrame tips.head()
一、直方圖distplot()
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)
- a 數(shù)據(jù)源
- bins 箱數(shù)
- hist、kde、rug 是否顯示箱數(shù)、密度曲線、數(shù)據(jù)分布,默認(rèn)顯示箱數(shù)和密度曲線不顯示數(shù)據(jù)分析
- {hist,kde,rug}_kws 通過(guò)字典形式設(shè)置箱數(shù)、密度曲線、數(shù)據(jù)分布的各個(gè)特征
- norm_hist 直方圖的高度是否顯示密度,默認(rèn)顯示計(jì)數(shù),如果kde設(shè)置為T(mén)rue高度也會(huì)顯示為密度
- color 顏色
- vertical 是否在y軸上顯示圖標(biāo),默認(rèn)為False即在x軸顯示,即豎直顯示
- axlabel 坐標(biāo)軸標(biāo)簽
- label 直方圖標(biāo)簽
fig = plt.figure(figsize=(12,5)) ax1 = plt.subplot(121) rs = np.random.RandomState(10) # 設(shè)定隨機(jī)數(shù)種子 s = pd.Series(rs.randn(100) * 100) sns.distplot(s,bins = 10,hist = True,kde = True,rug = True,norm_hist=False,color = 'y',label = 'distplot',axlabel = 'x') plt.legend() ax1 = plt.subplot(122) sns.distplot(s,rug = True, hist_kws={"histtype": "step", "linewidth": 1,"alpha": 1, "color": "g"}, # 設(shè)置箱子的風(fēng)格、線寬、透明度、顏色,風(fēng)格包括:'bar', 'barstacked', 'step', 'stepfilled' kde_kws={"color": "r", "linewidth": 1, "label": "KDE",'linestyle':'--'}, # 設(shè)置密度曲線顏色,線寬,標(biāo)注、線形 rug_kws = {'color':'r'} ) # 設(shè)置數(shù)據(jù)頻率分布顏色
二、密度圖
#密度曲線 kdeplot(data, data2=None, shade=False, vertical=False, kernel="gau",bw="scott", gridsize=100, cut=3, clip=None,? legend=True,cumulative=False,shade_lowest=True,cbar=False, cbar_ax=None,cbar_kws=None, ax=None, **kwargs)
- shade 是否填充與坐標(biāo)軸之間的
- bw 取值'scott' 、'silverman'或一個(gè)數(shù)值標(biāo)量,控制擬合的程度,類似直方圖的箱數(shù),設(shè)置的數(shù)量越大越平滑,越小越容易過(guò)度擬合
- shade_lowest 主要是對(duì)兩個(gè)變量分析時(shí)起作用,是否顯示最外側(cè)填充顏色,默認(rèn)顯示
- cbar 是否顯示顏色圖例
- n_levels 主要對(duì)兩個(gè)變量分析起作用,數(shù)據(jù)線的個(gè)數(shù)
數(shù)據(jù)分布rugplot(a, height=.05, axis="x", ax=None, **kwargs)
- height 分布線高度
- axis {'x','y'},在x軸還是y軸顯示數(shù)據(jù)分布
1.單個(gè)樣本數(shù)據(jù)分布密度圖
sns.kdeplot(s,shade = False, color = 'r',vertical = False)# 是否填充、設(shè)置顏色、是否水平 sns.kdeplot(s,bw=0.2, label="bw: 0.2",linestyle = '-',linewidth = 1.2,alpha = 0.5) sns.kdeplot(s,bw=2, label="bw: 2",linestyle = '-',linewidth = 1.2,alpha = 0.5,shade=True) sns.rugplot(s,height = 0.1,color = 'k',alpha = 0.5) #數(shù)據(jù)分布
2.兩個(gè)樣本數(shù)據(jù)分布密度圖
兩個(gè)維度數(shù)據(jù)生成曲線密度圖,以顏色作為密度衰減顯示。
rs = np.random.RandomState(2) # 設(shè)定隨機(jī)數(shù)種子 df = pd.DataFrame(rs.randn(100,2),columns = ['A','B']) sns.kdeplot(df['A'],df['B'],shade = True,cbar = True,cmap = 'Reds',shade_lowest=True, n_levels = 8)# 曲線個(gè)數(shù)(如果非常多,則會(huì)越平滑) plt.grid(linestyle = '--') plt.scatter(df['A'], df['B'], s=5, alpha = 0.5, color = 'k') #散點(diǎn) sns.rugplot(df['A'], color="g", axis='x',alpha = 0.5) #x軸數(shù)據(jù)分布 sns.rugplot(df['B'], color="r", axis='y',alpha = 0.5) #y軸數(shù)據(jù)分布
rs1 = np.random.RandomState(2) rs2 = np.random.RandomState(5) df1 = pd.DataFrame(rs1.randn(100,2)+2,columns = ['A','B']) df2 = pd.DataFrame(rs2.randn(100,2)-2,columns = ['A','B']) sns.set_style('darkgrid') sns.set_context('talk') sns.kdeplot(df1['A'],df1['B'],cmap = 'Greens',shade = True,shade_lowest=False) sns.kdeplot(df2['A'],df2['B'],cmap = 'Blues', shade = True,shade_lowest=False)
三、散點(diǎn)圖
jointplot() / JointGrid() / pairplot() /pairgrid()
1.jointplot()綜合散點(diǎn)圖
rs = np.random.RandomState(2) df = pd.DataFrame(rs.randn(200,2),columns = ['A','B']) sns.jointplot(x=df['A'], y=df['B'], # 設(shè)置x軸和y軸,顯示columns名稱 data=df, # 設(shè)置數(shù)據(jù) color = 'k', # 設(shè)置顏色 s = 50, edgecolor="w",linewidth=1, # 設(shè)置散點(diǎn)大小、邊緣線顏色及寬度(只針對(duì)scatter) kind = 'scatter', # 設(shè)置類型:“scatter”、“reg”、“resid”、“kde”、“hex” space = 0.1, # 設(shè)置散點(diǎn)圖和上方、右側(cè)直方圖圖的間距 size = 6, # 圖表大?。ㄗ詣?dòng)調(diào)整為正方形) ratio = 3, # 散點(diǎn)圖與直方圖高度比,整型 marginal_kws=dict(bins=15, rug=True,color='green') # 設(shè)置直方圖箱數(shù)以及是否顯示rug )
當(dāng)kind分別設(shè)置為其他4種“reg”、“resid”、“kde”、“hex”時(shí),圖表如下:
sns.jointplot(x=df['A'], y=df['B'],data=df,kind='reg',size=5) # sns.jointplot(x=df['A'], y=df['B'],data=df,kind='resid',size=5) # sns.jointplot(x=df['A'], y=df['B'],data=df,kind='kde',size=5) # sns.jointplot(x=df['A'], y=df['B'],data=df,kind='hex',size=5) #蜂窩圖
在密度圖中添加散點(diǎn)圖,先通過(guò)sns.jointplot()創(chuàng)建密度圖并賦值給變量,再通過(guò)變量.plot_joint()在密度圖中添加散點(diǎn)圖。
rs = np.random.RandomState(15) df = pd.DataFrame(rs.randn(300,2),columns = ['A','B']) g = sns.jointplot(x=df['A'], y=df['B'],data = df, kind="kde", color="pink",shade_lowest=False) #密度圖,并賦值給一個(gè)變量 g.plot_joint(plt.scatter,c="w", s=30, linewidth=1, marker="+") #在密度圖中添加散點(diǎn)圖
2.拆分綜合散點(diǎn)圖JointGrid()
上述綜合散點(diǎn)圖可分為上、右、中間三部分,設(shè)置屬性時(shí)對(duì)這三個(gè)參數(shù)都生效,JointGrid()可將這三部分拆開(kāi)分別設(shè)置屬性。
①拆分為中間+上&右 兩部分設(shè)置
# plot_joint() + plot_marginals() g = sns.JointGrid(x="total_bill", y="tip", data=tips)# 創(chuàng)建一個(gè)繪圖區(qū)域,并設(shè)置好x、y對(duì)應(yīng)數(shù)據(jù) g = g.plot_joint(plt.scatter,color="g", s=40, edgecolor="white") # 中間區(qū)域通過(guò)g.plot_joint繪制散點(diǎn)圖 plt.grid('--') g.plot_marginals(sns.distplot, kde=True, color="y") # h = sns.JointGrid(x="total_bill", y="tip", data=tips)# 創(chuàng)建一個(gè)繪圖區(qū)域,并設(shè)置好x、y對(duì)應(yīng)數(shù)據(jù) h = h.plot_joint(sns.kdeplot,cmap = 'Reds_r') # 中間區(qū)域通過(guò)g.plot_joint繪制散點(diǎn)圖 plt.grid('--') h.plot_marginals(sns.kdeplot, color="b")
②拆分為中間+上+右三個(gè)部分分別設(shè)置
# plot_joint() + ax_marg_x.hist() + ax_marg_y.hist() sns.set_style("white")# 設(shè)置風(fēng)格 tips = sns.load_dataset("tips") # 導(dǎo)入系統(tǒng)的小費(fèi)數(shù)據(jù) print(tips.head()) g = sns.JointGrid(x="total_bill", y="tip", data=tips)# 創(chuàng)建繪圖區(qū)域,設(shè)置好x、y對(duì)應(yīng)數(shù)據(jù) g.plot_joint(plt.scatter, color ='y', edgecolor = 'white') # 設(shè)置內(nèi)部散點(diǎn)圖scatter g.ax_marg_x.hist(tips["total_bill"], color="b", alpha=.6,bins=np.arange(0, 60, 3)) # 設(shè)置x軸直方圖,注意bins是數(shù)組 g.ax_marg_y.hist(tips["tip"], color="r", alpha=.6, orientation="horizontal", bins=np.arange(0, 12, 1)) # 設(shè)置y軸直方圖,需要orientation參數(shù) from scipy import stats g.annotate(stats.pearsonr) # 設(shè)置標(biāo)注,可以為pearsonr,spearmanr plt.grid(linestyle = '--')
3.pairplot()矩陣散點(diǎn)圖
矩陣散點(diǎn)圖類似pandas的pd.plotting.scatter_matrix(...),將數(shù)據(jù)從多個(gè)維度進(jìn)行兩兩對(duì)比。
對(duì)角線默認(rèn)顯示密度圖,非對(duì)角線默認(rèn)顯示散點(diǎn)圖。
sns.set_style("white") iris = sns.load_dataset("iris") print(iris.head()) sns.pairplot(iris, kind = 'scatter', # 散點(diǎn)圖/回歸分布圖 {‘scatter', ‘reg'} diag_kind="hist", # 對(duì)角線處直方圖/密度圖 {‘hist', ‘kde'} hue="species", # 按照某一字段進(jìn)行分類 palette="husl", # 設(shè)置調(diào)色板 markers=["o", "s", "D"], # 設(shè)置不同系列的點(diǎn)樣式(個(gè)數(shù)與hue分類的個(gè)數(shù)一致) height = 1.5, # 圖表大小 )
對(duì)原數(shù)據(jù)的局部變量進(jìn)行分析,可添加參數(shù)vars
sns.pairplot(iris,vars=["sepal_width", "sepal_length"], kind = 'reg', diag_kind="kde", hue="species", palette="husl")
plot_kws()和diag_kws()可分別設(shè)置對(duì)角線和非對(duì)角線的顯示:
sns.pairplot(iris, vars=["sepal_length", "petal_length"],diag_kind="kde", markers="+", plot_kws=dict(s=50, edgecolor="b", linewidth=1),# 設(shè)置非對(duì)角線點(diǎn)樣式 diag_kws=dict(shade=True,color='r',linewidth=1)# 設(shè)置對(duì)角線密度圖樣式 )
4.拆分綜合散點(diǎn)圖JointGrid()
類似JointGrid()的功能,將矩陣散點(diǎn)圖拆分為對(duì)角線和非對(duì)角線圖表分別設(shè)置顯示屬性。
①拆分為對(duì)角線和非對(duì)角線
# map_diag() + map_offdiag() g = sns.PairGrid(iris,hue="species",palette = 'hls',vars=["sepal_width", "sepal_length"]) g.map_diag(plt.hist, # 對(duì)角線圖表,plt.hist/sns.kdeplot histtype = 'barstacked', # 可選:'bar', 'barstacked', 'step', 'stepfilled' linewidth = 1, edgecolor = 'gray') g.map_offdiag(plt.scatter, # f非對(duì)角線其他圖表,plt.scatter/plt.bar... edgecolor="yellow", s=20, linewidth = 1, # 設(shè)置點(diǎn)顏色、大小、描邊寬度)
②拆分為對(duì)角線+對(duì)角線上+對(duì)角線下 3部分設(shè)置
# map_diag() + map_lower() + map_upper() g = sns.PairGrid(iris) g.map_diag(sns.kdeplot, lw=1.5,color='y',alpha=0.5) # 設(shè)置對(duì)角線圖表 g.map_upper(plt.scatter, color = 'r',s=8) # 設(shè)置對(duì)角線上端圖表顯示為散點(diǎn)圖 g.map_lower(sns.kdeplot,cmap='Blues_r') # 設(shè)置對(duì)角線下端圖表顯示為多密度分布圖
到此這篇關(guān)于Python seaborn數(shù)據(jù)可視化繪圖(直方圖,密度圖,散點(diǎn)圖)的文章就介紹到這了,更多相關(guān)Python seaborn 繪圖內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python Django里CSRF 對(duì)應(yīng)策略詳解
這篇文章主要介紹了python Django里CSRF 對(duì)應(yīng)策略詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08通過(guò)淘寶數(shù)據(jù)爬蟲(chóng)學(xué)習(xí)python?scrapy?requests與response對(duì)象
本文主要介紹了通過(guò)淘寶數(shù)據(jù)爬蟲(chóng)學(xué)習(xí)python?scrapy?requests與response對(duì)象,首先從Resquest和Response對(duì)象開(kāi)始展開(kāi)詳細(xì)文章,需要的小伙伴可以參考一下2022-05-05python獲取異常信息exc_info和print_exc的使用
python通過(guò)sys.exc_info獲取異常信息,通過(guò)traceback.print_exc打印堆棧信息,包括錯(cuò)誤類型和錯(cuò)誤位置等信息,本文就來(lái)介紹一下具體用法,感興趣的可以了解一下2023-12-12Python命令行定時(shí)任務(wù)自動(dòng)化工作流程
本文介紹如何使用Python編寫(xiě)定時(shí)任務(wù),以自動(dòng)執(zhí)行命令行任務(wù)。您將學(xué)習(xí)如何安排定期的任務(wù),處理任務(wù)結(jié)果,以及如何使用Python自動(dòng)化工作流程,從而提高工作效率。無(wú)需手動(dòng)執(zhí)行重復(fù)任務(wù),Python幫您搞定2023-04-04python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5表單布局控件QFormLayout詳細(xì)使用方法與實(shí)例
這篇文章主要介紹了python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5布局控件QFormLayout詳細(xì)使用方法與實(shí)例,需要的朋友可以參考下2020-03-03Flask?+?MySQL如何實(shí)現(xiàn)用戶注冊(cè),登錄和登出的項(xiàng)目實(shí)踐
本文主要介紹了Flask?+?MySQL?如何實(shí)現(xiàn)用戶注冊(cè),登錄和登出的項(xiàng)目實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06詳解在python操作數(shù)據(jù)庫(kù)中游標(biāo)的使用方法
這篇文章主要介紹了在python操作數(shù)據(jù)庫(kù)中游標(biāo)的使用方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-11-11Python通過(guò)串口實(shí)現(xiàn)收發(fā)文件
這篇文章主要為大家詳細(xì)介紹了Python如何通過(guò)串口實(shí)現(xiàn)收發(fā)文件功能,文中的示例代碼簡(jiǎn)潔易懂,具有一定的借鑒價(jià)值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11