觀測兩個變量之間的分布關系 ------ 最好用散點圖
兩個便量間的分布關系:
1 # 生成一個多維正態分布的隨機數,分別傳入參數均值和協方差矩陣 2 mean, cov = [0, 1], [(1, .5), (.5, 1)] 3 data = np.random.multivariate_normal(mean, cov, 200) 4 df = pd.DataFrame(data, columns=["x", "y"]) 5 sns.jointplot(x="x", y="y", data=df) 6 # 在圖中添加回歸線 7 sns.jointplot(x="x", y="y", data=df, kind="reg") 8 plt.show()
運行結果:
用 “類蜂窩” 結構展示數據的分布:
1 x, y = np.random.multivariate_normal(mean, cov, 1000).T 2 with sns.axes_style("white"): 3 sns.jointplot(x=x, y=y, kind="hex", color="k") 4 plt.show()
運行結果:
多維數據間的分布關系
1 iris = sns.load_dataset("iris") 2 sns.pairplot(iris) 3 plt.show()
運行結果:
繪制回歸關系
regplot()和lmplot()都可以繪制回歸關系,推薦regplot()
1 tips = sns.load_dataset("tips") 2 print(tips.head()) 3 sns.regplot(x="total_bill", y="tip", data=tips) 4 sns.lmplot(x="total_bill", y="tip", data=tips) 5 plt.show()
運行結果:
用DataFrame數據畫圖
用 "dataset == 'I' " 的數據畫圖;用"dataset == 'II' " 的數據畫圖
1 anscombe = sns.load_dataset("anscombe") 2 print(anscombe.head()) 3 print(type(anscombe)) 4 # ci 置信區間 query 查詢布爾表達式所在的數據; scatter_kws={"s": 80}設置點的大小 5 sns.regplot(x="x", y="y", data=anscombe.query("dataset == 'I'"), 6 ci=None, scatter_kws={"s": 80}) 7 # order=2 表示用二次多項式擬合 8 sns.lmplot(x="x", y="y", data=anscombe.query("dataset == 'II'"), 9 ci=None, order=2, scatter_kws={"s": 40}) 10 plt.show()
運行結果:
根據某屬性的不同類別繪制曲線
根據一個屬性按類別繪制圖像
1 tips = sns.load_dataset("tips") 2 sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips) 3 # hue 列名分割 4 sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, 5 markers=["o", "*"], palette="Set1") 6 plt.show()
運行結果:
按兩個屬性的類別繪制,
這里 hue 參數指定分類單調屬性;col="time" 指定繪制圖的時候將time的類別繪制在一行,如time有兩個類別,
就繪制兩列,如果加一個參數row,那么row指定的屬性有幾個類別就會繪制幾行。
1 sns.lmplot(x="total_bill", y="tip", hue="smoker", col="time", data=tips) 2 plt.show()
1 sns.lmplot(x="total_bill", y="tip", hue="smoker", 2 col="time", row="sex", data=tips) 3 plt.show()
運行結果:
ax參數會改變坐標的縮放;如果指定的col參數對應的屬性有4個類別,那么畫出來就是1行4列,這樣不太美觀,
我們可以用col_wrap=2 設定為2行。aspect=.5 你也可以使用這個參數設置長寬比。size參數已經停用,請使用
height表示“size”。
1 f, ax = plt.subplots(figsize=(5, 5)) 2 sns.regplot(x="total_bill", y="tip", data=tips, ax=ax) 3 plt.show() 4 sns.regplot(x="total_bill", y="tip", data=tips) 5 plt.show() 6 sns.lmplot(x="total_bill", y="tip", col="day", 7 data=tips, col_wrap=2, height=4)
8 plt.show()
運行結果: