單變量分析繪圖
直方圖
import seaborn as sns
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy import stats,integrate
import pandas as pd
%matplotlib inline
sns.set(color_codes=True)
np.random.seed(sum(map(ord,"distribution")))
x = np.random.normal(size=100)
sns.distplot(x,bins=20,kde=True)
#bins: 設置分桶數
#kde控制是否畫kde曲線
map()函數:
第一個參數接受一個函數名,後面的參數接受一個或多個可迭代的序列,返回的是一個集合。
把函數依次作用在list中的每一個元素上,得到一個新的list並返回。注意,map不改變原list,而是返回一個新list。
ord()函數:
ord()函數它以一個字符(長度爲1的字符串)作爲參數,返回對應的ASCII數值,或者Unicode數值。如果所給的Unicode字符超出了你的Python定義範圍,則會引發一個TypeError的異常。
np.random.seed()函數
設置相同的seed,每次生成的隨機數相同。
數據分佈情況
x = np.random.gamma(6, size=200)
sns.distplot(x, kde=False, fit=stats.gamma) #實例化伽瑪分佈
根據均值和協方差生成數據
np.random.multivariate_normal生成一個服從多元正態分佈的數組
multivariate_normal(mean, cov, size=None, check_valid=None, tol=None)
mean:均值,維度爲1,必選參數;
cov:協方差矩陣,必選參數;
size: 指定生成矩陣的維度,若size=(1, 1, 2),則輸出的矩陣的 shape 即形狀爲 1X1X2XN(N爲mean的#長度);
check_valid:可取值 warn,raise以及ignore;
tol:檢查協方差矩陣奇異值時的公差,float類型
mean, cov = [0, 1], [(1, .5), (.5, 1)]
#兩個相關的正態分佈
data = np.random.multivariate_normal(mean, cov, 200)
#依據指定的均值和協方差生成數據,生成二維數組
df = pd.DataFrame(data, columns=["x", "y"])
df.tail()
x | y | |
---|---|---|
195 | -0.885440 | -0.275349 |
196 | -0.678798 | 1.505844 |
197 | 1.601188 | 2.096382 |
198 | -0.398727 | 1.388353 |
199 | -0.051887 | 0.427285 |
觀測兩個變量之間的分佈關係最好用散點圖 (數據量較小)
sns.jointplot(x="x", y="y", data=df);
數據量較大的情況
x,y = np.random.multivariate_normal(mean,cov,1000).T
with sns.axes_style('white'):
sns.jointplot(x=x,y=y,kind='hex',color='g') #kind=’hex’——六角箱圖
迴歸分析圖
np.random.seed(sum(map(ord,'regression')))
tips = sns.load_dataset('tips') #tips爲Seaborn內置數據集
#tips.head()
sns.regplot(x='total_bill',y='tip',data=tips)
sns.regplot(x='size',y='tip',data=tips)
sns.regplot(x='size',y='tip',data=tips,x_jitter=.05) #數據橫向浮動0.05
多變量分析繪圖
sns.set(style='whitegrid',color_codes=True)
np.random.seed(sum(map(ord,"categorical")))
titanic = sns.load_dataset('titanic')
tips = sns.load_dataset('tips')
iris = sns.load_dataset('iris')
sns.stripplot(x='day',y='total_bill',hue='day',data=tips,jitter=True)
stripplot()按照x軸裏的類別進行分類
jitter=True,使集中在一起的數據往左往右偏移
hue=' day' 用不同的顏色標識分類
sns.swarmplot(x='day',y='total_bill',hue='sex',data=tips)
swarmplot()分簇散點圖
盒圖
IQR即統計學概念四分位距,第一四分位和第三四分位之間的距離
N = 1.5IQR 如果一個值>Q3+N,或者<Q1-N,則爲離羣點
sns.violinplot(x='total_bill',y='day',hue='time',data=tips)
violinplot()小提琴圖,越大的地方說明數據出現在的頻率越高
分類屬性繪圖
sns.violinplot(x='day',y='total_bill',hue='sex',data=tips,split=True)
#split 對數據進行分類
sns.violinplot(x='day',y='total_bill',data=tips,inner=None)
sns.swarmplot(x='day',y='total_bill',data=tips,color='w',alpha=.9)
顯示值的集中趨勢可以用條形圖
sns.barplot(x='sex',y='survived',hue='class',data=titanic)
點圖可以更好的描述單一變量變化趨勢
sns.pointplot(x='sex',y='survived',hue='class',data=titanic)
對比不同性別活下的來概率
sns.pointplot(x='class',y='survived',hue='sex',data=titanic,
palette={'male':'g','female':'m'},
markers=['*','o'],linestyle=['-','--']);
自定義點圖
多層面板分類圖(最常用)
sns.factorplot(x='day',y='total_bill',hue='smoker',data=tips,kind='bar')
sns.factorplot(x='day',y='total_bill',hue='smoker',data=tips,col='time',kind='swarm')
sns.factorplot(x='time',y='total_bill',hue='smoker',data=tips,col='day',kind='box',size=4,aspect=.5)
aspect=0.5 設置長寬比
facetgrid的使用方法
tips = sns.load_dataset('tips')
g = sns.FacetGrid(tips,col='time') #實例化facetgrid
g.map(plt.hist,'tip')
g = sns.FacetGrid(tips,col='sex',hue='smoker')
g.map(plt.scatter,'total_bill','tip',alpha=.7)
g.add_legend()
scatter表示散點圖
g.add_legend()加入標註
g = sns.FacetGrid(tips,row='smoker',col='time',margin_titles=True)
g.map(sns.regplot,'size','total_bill',color='.1',fit_reg=True,x_jitter=.1)
fit_reg=True 顯示迴歸線
from pandas import Categorical
ordered_days = tips.day.value_counts().index #tips數據集中原來的順序
ordered_days = Categorical(['Thur','Fri','Sat','Sun']) #自己設置的順序
print(ordered_days)
g = sns.FacetGrid(tips,row='day',row_order=ordered_days,size=1.7,aspect=4)
g.map(sns.boxplot,'total_bill')
Facetgrid繪製多變量
pal = dict(Lunch='seagreen',Dinner='gray')
g = sns.FacetGrid(tips,hue='time',palette=pal,size=5)
g.map(plt.scatter,'total_bill','tip',s=20,alpha=.7,linewidth=.5,edgecolor='white')
g.add_legend()
s=20 設置圖中標識圓點大小
alpha=.7設置對比度
with sns.axes_style('white'):
g = sns.FacetGrid(tips,row='sex',col='smoker',margin_titles=True,size=2.5)
g.map(plt.scatter,'total_bill','tip',color='#334488',edgecolor='white',lw=.9);
g.set_axis_labels('Total bill(US Dollars)','Tip');
g.set(xticks=[10,30,50],yticks=[2,6,10]);
g.fig.subplots_adjust(wspace=.5,hspace=.5) #設置每個子圖之間的距離
這裏出現四個子圖的原因是:smoker和sex各種兩種可能
iris = sns.load_dataset('iris')
g = sns.PairGrid(iris)
g.map(plt.scatter)
對圖
g = sns.PairGrid(iris,vars=['sepal_length','sepal_width'],hue='species')
g.map(plt.scatter); #取鳶尾花數據集中兩個特徵進行成圖