seaborn分布數據可視化:直方圖|密度圖|散點圖

系統自帶的數據表格(存放在github上https://github.com/mwaskom/seaborn-data),使用時通過sns.load_dataset('表名稱')即可,結果為一個DataFrame。

print(sns.get_dataset_names())   #獲取所有數據表名稱
# ['anscombe', 'attention', 'brain_networks', 'car_crashes', 'diamonds', 'dots', 'exercise', 'flights', 
# 'fmri', 'gammas', 'iris', 'mpg', 'planets', 'tips', 'titanic']
tips = sns.load_dataset('tips')  #導入小費tips數據表,返回一個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 數據源
  • bins 箱數
  • hist、kde、rug 是否顯示箱數、密度曲線、數據分布,默認顯示箱數和密度曲線不顯示數據分析
  • {hist,kde,rug}_kws 通過字典形式設置箱數、密度曲線、數據分布的各個特征
  • norm_hist 直方圖的高度是否顯示密度,默認顯示計數,如果kde設置為True高度也會顯示為密度
  • color 顏色
  • vertical 是否在y軸上顯示圖標,默認為False即在x軸顯示,即豎直顯示
  • axlabel 坐標軸標簽
  • label 直方圖標簽
fig = plt.figure(figsize=(12,5))
ax1 = plt.subplot(121)
rs = np.random.RandomState(10)  # 設定隨機數種子
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"},  # 設置箱子的風格、線寬、透明度、顏色,風格包括:'bar', 'barstacked', 'step', 'stepfilled'        kde_kws={"color": "r", "linewidth": 1, "label": "KDE",'linestyle':'--'},   # 設置密度曲線顏色,線寬,標注、線形rug_kws = {'color':'r'} )  # 設置數據頻率分布顏色

二、密度圖

密度曲線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 是否填充與坐標軸之間的
  • bw 取值'scott' 、'silverman'或一個數值標量,控制擬合的程度,類似直方圖的箱數,設置的數量越大越平滑,越小越容易過度擬合
  • shade_lowest 主要是對兩個變量分析時起作用,是否顯示最外側填充顏色,默認顯示
  • cbar 是否顯示顏色圖例
  • n_levels 主要對兩個變量分析起作用,數據線的個數

數據分布rugplot(a, height=.05, axis="x", ax=None, **kwargs)

  • height 分布線高度
  • axis {'x','y'},在x軸還是y軸顯示數據分布

1.單個樣本數據分布密度圖?

sns.kdeplot(s,shade = False, color = 'r',vertical = False)# 是否填充、設置顏色、是否水平
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)  #數據分布

2.兩個樣本數據分布密度圖

兩個維度數據生成曲線密度圖,以顏色作為密度衰減顯示。

rs = np.random.RandomState(2)  # 設定隨機數種子
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)# 曲線個數(如果非常多,則會越平滑) 
plt.grid(linestyle = '--')
plt.scatter(df['A'], df['B'], s=5, alpha = 0.5, color = 'k') #散點
sns.rugplot(df['A'], color="g", axis='x',alpha = 0.5) #x軸數據分布
sns.rugplot(df['B'], color="r", axis='y',alpha = 0.5) #y軸數據分布

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)

三、散點圖

jointplot() /?JointGrid() /?pairplot() /pairgrid()

1.jointplot()綜合散點圖

rs = np.random.RandomState(2)  
df = pd.DataFrame(rs.randn(200,2),columns = ['A','B'])sns.jointplot(x=df['A'], y=df['B'],  # 設置x軸和y軸,顯示columns名稱data=df,   # 設置數據color = 'k',   # 設置顏色s = 50, edgecolor="w",linewidth=1,  # 設置散點大小、邊緣線顏色及寬度(只針對scatter)kind = 'scatter',   # 設置類型:“scatter”、“reg”、“resid”、“kde”、“hex”space = 0.1,  # 設置散點圖和上方、右側直方圖圖的間距size = 6,   # 圖表大小(自動調整為正方形)ratio = 3,  # 散點圖與直方圖高度比,整型marginal_kws=dict(bins=15, rug=True,color='green')  # 設置直方圖箱數以及是否顯示rug)  

當kind分別設置為其他4種“reg”、“resid”、“kde”、“hex”時,圖表如下。

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) #蜂窩圖

?

在密度圖中添加散點圖,先通過sns.jointplot()創建密度圖并賦值給變量,再通過變量.plot_joint()在密度圖中添加散點圖。

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.plot_joint(plt.scatter,c="w", s=30, linewidth=1, marker="+")  #在密度圖中添加散點圖

2.拆分綜合散點圖JointGrid()?

上述綜合散點圖可分為上、右、中間三部分,設置屬性時對這三個參數都生效,JointGrid()可將這三部分拆開分別設置屬性。

①拆分為中間+上&右 兩部分設置

# plot_joint() + plot_marginals()
g = sns.JointGrid(x="total_bill", y="tip", data=tips)# 創建一個繪圖區域,并設置好x、y對應數據
g = g.plot_joint(plt.scatter,color="g", s=40, edgecolor="white")   # 中間區域通過g.plot_joint繪制散點圖
plt.grid('--')g.plot_marginals(sns.distplot, kde=True, color="y")     #

h = sns.JointGrid(x="total_bill", y="tip", data=tips)# 創建一個繪圖區域,并設置好x、y對應數據
h = h.plot_joint(sns.kdeplot,cmap = 'Reds_r')   # 中間區域通過g.plot_joint繪制散點圖
plt.grid('--')
h.plot_marginals(sns.kdeplot, color="b") 

?

②拆分為中間+上+右三個部分分別設置

# plot_joint() + ax_marg_x.hist() + ax_marg_y.hist()

sns.set_style("white")# 設置風格
tips = sns.load_dataset("tips") # 導入系統的小費數據
print(tips.head())g = sns.JointGrid(x="total_bill", y="tip", data=tips)# 創建繪圖區域,設置好x、y對應數據

g.plot_joint(plt.scatter, color ='y', edgecolor = 'white')  # 設置內部散點圖scatter
g.ax_marg_x.hist(tips["total_bill"], color="b", alpha=.6,bins=np.arange(0, 60, 3))  # 設置x軸直方圖,注意bins是數組
g.ax_marg_y.hist(tips["tip"], color="r", alpha=.6, orientation="horizontal", bins=np.arange(0, 12, 1)) # 設置y軸直方圖,需要orientation參數from scipy import stats
g.annotate(stats.pearsonr)  # 設置標注,可以為pearsonr,spearmanr

plt.grid(linestyle = '--')

3.pairplot()矩陣散點圖

矩陣散點圖類似pandas的pd.plotting.scatter_matrix(...),將數據從多個維度進行兩兩對比。

對角線默認顯示密度圖,非對角線默認顯示散點圖。

sns.set_style("white")
iris = sns.load_dataset("iris")
print(iris.head())
sns.pairplot(iris,kind = 'scatter',  # 散點圖/回歸分布圖 {‘scatter’, ‘reg’}  diag_kind="hist",  # 對角線處直方圖/密度圖 {‘hist’, ‘kde’}hue="species",   # 按照某一字段進行分類palette="husl",  # 設置調色板markers=["o", "s", "D"],  # 設置不同系列的點樣式(個數與hue分類的個數一致)height = 1.5,   # 圖表大小)

?

對原數據的局部變量進行分析,可添加參數vars

sns.pairplot(iris,vars=["sepal_width", "sepal_length"], kind = 'reg', diag_kind="kde", hue="species", palette="husl")

?

plot_kws()和diag_kws()可分別設置對角線和非對角線的顯示

sns.pairplot(iris, vars=["sepal_length", "petal_length"],diag_kind="kde", markers="+",plot_kws=dict(s=50, edgecolor="b", linewidth=1),# 設置非對角線點樣式diag_kws=dict(shade=True,color='r',linewidth=1)# 設置對角線密度圖樣式)

4..拆分綜合散點圖JointGrid()?

類似JointGrid()的功能,將矩陣散點圖拆分為對角線和非對角線圖表分別設置顯示屬性。

①拆分為對角線和非對角線

# map_diag() + map_offdiag()

g = sns.PairGrid(iris,hue="species",palette = 'hls',vars=["sepal_width", "sepal_length"])
g.map_diag(plt.hist, # 對角線圖表,plt.hist/sns.kdeplothisttype = 'barstacked',   # 可選:'bar', 'barstacked', 'step', 'stepfilled'linewidth = 1, edgecolor = 'gray')           
g.map_offdiag(plt.scatter, # f非對角線其他圖表,plt.scatter/plt.bar...edgecolor="yellow", s=20, linewidth = 1,   # 設置點顏色、大小、描邊寬度)   

?

? ??

?

②拆分為對角線+對角線上+對角線下 3部分設置

# map_diag() + map_lower() + map_upper()
g = sns.PairGrid(iris)
g.map_diag(sns.kdeplot, lw=1.5,color='y',alpha=0.5)   # 設置對角線圖表
g.map_upper(plt.scatter, color = 'r',s=8)     # 設置對角線上端圖表顯示為散點圖
g.map_lower(sns.kdeplot,cmap='Blues_r') # 設置對角線下端圖表顯示為多密度分布圖

? ? ? ?

?

轉載于:https://www.cnblogs.com/Forever77/p/11399523.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391569.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391569.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391569.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

如何成為一個優秀的程序員_如何成為一名優秀的程序員

如何成為一個優秀的程序員by Amy M Haddad通過艾米M哈達德(Amy M Haddad) 如何成為一名優秀的程序員 (How to be a great programmer) What sets apart the really great programmers?是什么使真正出色的程序員與眾不同? As we all know, great programmers buil…

pymc3使用_使用PyMC3了解飛機事故趨勢

pymc3使用Visually exploring historic airline accidents, applying frequentist interpretations and validating changing trends with PyMC3.使用PyMC3直觀地瀏覽歷史性航空事故,應用常識性解釋并驗證變化趨勢。 前言 (Preface) On the 7th of August this yea…

視頻監控業務上云方案解析

摘要:阿里云針對安防監控服務在傳統IT架構下面臨的上述問題,基于阿里云存儲服務,提供視頻監控解決方案。從2015年推出視頻監控存儲與播放解決方案以來,幫助大量的視頻監控企業解決了上云的過程中遇到的問題,針對不同的…

leetcode 341. 扁平化嵌套列表迭代器(dfs)

給你一個嵌套的整型列表。請你設計一個迭代器,使其能夠遍歷這個整型列表中的所有整數。 列表中的每一項或者為一個整數,或者是另一個列表。其中列表的元素也可能是整數或是其他列表。 示例 1: 輸入: [[1,1],2,[1,1]] 輸出: [1,1,2,1,1] 解釋: 通過重復…

爬蟲結果數據完整性校驗

數據完整性分為三個方面: 1、域完整性(列) 限制輸入數據的類型,及范圍,或者格式,如性別字段必須是“男”或者“女”,不允許其他數據插入,成績字段只能是0-100的整型數據,…

go map數據結構

map數據結構 key-value的數據結構,又叫字典或關聯數組 聲明:var map1 map[keytype]valuetype var a map[string]string var a map[string]int var a map[int]string var a map[string]map[string]string備注:聲明是不會分配內存的&#xff0c…

吳恩達神經網絡1-2-2_圖神經網絡進行藥物發現-第2部分

吳恩達神經網絡1-2-2預測毒性 (Predicting Toxicity) 相關資料 (Related Material) Jupyter Notebook for the article Jupyter Notebook的文章 Drug Discovery with Graph Neural Networks — part 1 圖神經網絡進行藥物發現-第1部分 Introduction to Cheminformatics 化學信息…

android初學者_適用于初學者的Android廣播接收器

android初學者Let’s say you have an application that depends on a steady internet connection. You want your application to get notified when the internet connection changes. How do you do that?假設您有一個依賴穩定互聯網連接的應用程序。 您希望您的應用程序在…

Android熱修復之 - 阿里開源的熱補丁

1.1 基本介紹     我們先去github上面了解它https://github.com/alibaba/AndFix 這里就有一個概念那就AndFix.apatch補丁用來修復方法,接下來我們看看到底是怎么實現的。1.2 生成apatch包      假如我們收到了用戶上傳的崩潰信息,我們改完需要修復…

leetcode 456. 132 模式(單調棧)

給你一個整數數組 nums &#xff0c;數組中共有 n 個整數。132 模式的子序列 由三個整數 nums[i]、nums[j] 和 nums[k] 組成&#xff0c;并同時滿足&#xff1a;i < j < k 和 nums[i] < nums[k] < nums[j] 。 如果 nums 中存在 132 模式的子序列 &#xff0c;返回…

seaborn分類數據可視:散點圖|箱型圖|小提琴圖|lv圖|柱狀圖|折線圖

一、散點圖stripplot( ) 與swarmplot&#xff08;&#xff09; 1.分類散點圖stripplot( ) 用法stripplot(xNone, yNone, hueNone, dataNone, orderNone, hue_orderNone,jitterTrue, dodgeFalse, orientNone, colorNone, paletteNone,size5, edgecolor"gray", linewi…

數據圖表可視化_數據可視化十大最有用的圖表

數據圖表可視化分析師每天使用的最佳數據可視化圖表列表。 (List of best data visualization charts that Analysts use on a daily basis.) Presenting information or data in a visual format is one of the most effective ways. Researchers have proved that the human …

javascript實現自動添加文本框功能

轉自&#xff1a;http://www.cnblogs.com/damonlan/archive/2011/08/03/2126046.html 昨天&#xff0c;我們公司的網絡小組決定為公司做一個內部的網站&#xff0c;主要是為員工比如發布公告啊、填寫相應信息、投訴、問題等等需求。我那同事給了我以下需求&#xff1a; 1.點擊一…

從Mysql slave system lock延遲說開去

本文主要分析 sql thread中system lock出現的原因&#xff0c;但是筆者并明沒有系統的學習過master-slave的代碼&#xff0c;這也是2018年的一個目標&#xff0c;2018年我都排滿了&#xff0c;悲劇。所以如果有錯誤請指出&#xff0c;也作為一個筆記用于后期學習。同時也給出筆…

傳智播客全棧_播客:從家庭學生到自學成才的全棧開發人員

傳智播客全棧In this weeks episode of the freeCodeCamp podcast, Abbey chats with Madison Kanna, a full-stack developer who works remotely for Mediavine. Madison describes how homeschooling affected her future learning style, how she tackles imposter syndrom…

leetcode 82. 刪除排序鏈表中的重復元素 II(map)

解題思路 map記錄數字出現的次數&#xff0c;出現次數大于1的數字從鏈表中移除 代碼 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val val; }* ListNode(…

python 列表、字典多排序問題

版權聲明&#xff1a;本文為博主原創文章&#xff0c;遵循 CC 4.0 by-sa 版權協議&#xff0c;轉載請附上原文出處鏈接和本聲明。本文鏈接&#xff1a;https://blog.csdn.net/justin051/article/details/84289189Python使用sorted函數來排序&#xff1a; l [2,1,3,5,7,3]print…

接facebook廣告_Facebook廣告分析

接facebook廣告Is our company’s Facebook advertising even worth the effort?我們公司的Facebook廣告是否值得努力&#xff1f; 題&#xff1a; (QUESTION:) A company would like to know if their advertising is effective. Before you start, yes…. Facebook does ha…

如何創建自定義進度欄

Originally published on www.florin-pop.com最初發布在www.florin-pop.com The theme for week #14 of the Weekly Coding Challenge is: 每周編碼挑戰第14周的主題是&#xff1a; 進度條 (Progress Bar) A progress bar is used to show how far a user action is still in…

基于SpringBoot的CodeGenerator

title: 基于SpringBoot的CodeGenerator tags: SpringBootMybatis生成器PageHelper categories: springboot date: 2017-11-21 15:13:33背景 目前組織上對于一個基礎的crud的框架需求較多 因此選擇了SpringBoot作為基礎選型。 Spring Boot是由Pivotal團隊提供的全新框架&#xf…