Python 資料視覺化筆記(二) — 使用Seaborn繪圖

Yanwei Liu
8 min readMar 30, 2019

Seaborn

初始化

import seaborn as sns
import pandas as pd
%matplotlib inline
pd.set_option("display.max_rows", 1000) #設定最大能顯示1000rows
pd.set_option("display.max_columns", 1000) #設定最大能顯示1000columns

解決plot不能顯示中文問題

from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei']
mpl.rcParams['axes.unicode_minus'] = False
sns.pairplot(df) #使用seaborn繪製多變量圖
sns.pairplot(df, vars=['PM2.5', 'AQI','WindSpeed']) #指定3個變數繪圖

讀取檔案

sns.load_dataset('tips') #讀取內建資料
tips = sns.load_dataset('tips') #讀取內建資料
tips.head()

繪圖

直方圖(含KDE)(distplot)
sns.distplot(tips['total_bill'])
移除KDE隻留直方圖(distplot)
sns.distplot(tips['total_bill'],kde=False,bins=30)
結合兩種圖及雙變數資料(joinplot)
sns.jointplot(x='total_bill',y='tip',data=tips,kind='scatter')
#kind的選擇有scatter、reg、resid、kde、hex
sns.jointplot(x='total_bill',y='tip',data=tips,kind='hex')
sns.jointplot(x='total_bill',y='tip',data=tips,kind='reg')
折線圖(pointplot)
sns.pointplot(x="day",y="tip",data=tips)
多變量圖(pairplot)
sns.pairplot(tips)
#可設定需要進行多變量繪圖的欄位
X = df[['PM25', 'AQI', 'SO2','CO2']]
sns.pairplot(X)
#可使用hue進一步區分不同變數palette=顏色主題
sns.pairplot(tips,hue='sex',palette='coolwarm')
單一變數於單一X軸上畫出(rugplot)
sns.rugplot(tips['total_bill'])
核密度圖(kdeplot)
sns.kdeplot(tips['total_bill'])
sns.rugplot(tips['tip'])
柱狀圖(barplot)
import numpy as np
sns.barplot(x='sex',y='total_bill',data=tips,estimator=np.std)
計算單一變數的次數(countplot)
sns.countplot(x='sex',data=tips)
盒鬚圖(boxplot):檢查資料分散程度
#製作盒鬚圖,hue可作為進一步區分特定變數的工具
sns.boxplot(x='day',y='total_bill',data=tips,hue='smoker')
小提琴圖(violinplot)
#小提琴圖比起盒鬚圖更能強調資料密集在哪
sns.violinplot(x='day',y='total_bill',data=tips,hue='sex',split=True)
類別資料散布圖(stripplot)
#一個變數為資料,一個變數為類別,點容易重疊在一起,使用jitter=True可以解決
#使用hue可以進一步區分變數,dodge則是可以將hue區分的變數分成兩行
sns.stripplot(x=’day’,y=’total_bill’,data=tips,jitter=True,hue=’sex’,dodge=True)
群圖(swarmplot)
#是strip和violin的混合,會將類別資料分散顯示
sns.violinplot(x='day',y='total_bill',data=tips)
sns.swarmplot(x='day',y='total_bill',data=tips,color='black')
因素圖(factorplot)
#使用factorplot的話,則可在參數中設定kind=圖表名稱來設定圖表
sns.factorplot(x='day',y='total_bill',data=tips,kind='bar')
矩陣圖
1.corr()(關聯係數熱點圖)
tc = tips.corr()
sns.heatmap(tc,annot=True,cmap='coolwarm')
#先將資料轉成matrix,再直接用heatmap()即可。annot=True代表會出現數值。
cmap=顏色主題。
2.pivot table(樞紐分析圖)
#建立樞紐分析表
fp=flights.pivot_table(index='month',columns='year',values='passengers')
#linecolor設定每個資料點外框顏色,linewidths設定資料點外框寬度
sns.heatmap(fp,cmap='magma',linecolor='white',linewidths=1)
3.clustermap
#clustermap使用hierarchal clustering來建立heatmap。standard_scale等於資料比例尺
sns.clustermap(fp,cmap='coolwarm',standard_scale=1)
迴歸圖(lmplot)
#lmplot(x,y,data)
#hue可進一步區分第三個變數,markers則可讓hue想區分的變數資料符號不同
#scatter_kws={'key':value}可改變資料點的大小
sns.lmplot(x='total_bill',y='tip',data=tips,hue='sex',markers=['o','v'],scatter_kws={'s':100})
#col=第三變數,row=第四變數
#aspect ratio=長寬比,height=尺寸
sns.lmplot(x='total_bill',y='tip',data=tips,col='sex',row='time',aspect=1,height=4)

建立格子(Grid)

PairGrid#使用鳶尾花資料集練習
iris=sns.load_dataset('iris')
iris.head()
#檢查鳶尾花資料集品種有幾種
iris['species'].unique()
#PairGrid屬於subplot grid,類似pairplot,隻是客製化程度更高
g = sns.PairGrid(iris)
g.map_diag(sns.distplot)
g.map_upper(plt.scatter)
g.map_lower(sns.kdeplot)
Facet Grid
#FacetGrid是一種常見基於資料變數來建立grid(格子)的方法
g = sns.FacetGrid(data=tips,col='time',row='smoker')
g.map(plt.scatter,'total_bill','tip')

圖表風格與顏色

#style設定圖表風格
sns.set_style('ticks')
sns.countplot(x='sex',data=tips)
#despine()隻會去掉表格外框右邊及上面的線,如果所有外框都不要則額外設定
sns.despine(left=True,bottom=True)
#可以設定figuresize
plt.figure(figsize=[12,3])
sns.countplot(x='sex',data=tips)
#set_context可設定該圖表預定想放在哪種文件上展示
sns.set_context('poster')
sns.countplot(x='sex',data=tips)

--

--