Python繪圖總結(seaborn篇)之線性關係
阿新 • • 發佈:2019-02-05
%matplotlib inline
import numpy as np
import pandas as pd
from scipy import stats, integrate
import seaborn as sns
import matplotlib.pyplot as plt
# seaborn中文亂碼解決方案
from matplotlib.font_manager import FontProperties
myfont=FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf',size=14)
sns.set(font=myfont.get_name())
np.random.seed(sum(map(ord, "regression")))
tips = sns.load_dataset("tips")
線性迴歸
1、regplot()
# 簡單使用regplot()
sns.regplot(x="total_bill", y="tip", data=tips)
2、lmplot()
# 簡單使用lmplot()
sns.lmplot(x="total_bill", y="tip", data=tips)
# x_jitter 表示沿軸隨機分佈,相對避免重疊
sns.lmplot(x="size" , y="tip", data=tips, x_jitter=.05)
sns.lmplot(x="size", y="tip", data=tips, x_estimator=np.mean)
擬合不同模型
anscombe = sns.load_dataset("anscombe")
anscombe[::-5]
dataset | x | y | |
---|---|---|---|
43 | IV | 8.0 | 6.89 |
38 | IV | 8.0 | 7.04 |
33 | IV | 8.0 | 6.58 |
28 | III | 6.0 | 6.08 |
23 | III | 8.0 | 6.77 |
18 | II | 4.0 | 3.10 |
13 | II | 13.0 | 8.74 |
8 | I | 12.0 | 10.84 |
3 | I | 9.0 | 8.81 |
1、lmplot()
# 原來資料還可以這樣查詢 anscombe.query("dataset == 'I'")
sns.lmplot(x="x", y="y", data=anscombe.query("dataset == 'I'"), ci=None, scatter_kws={"s": 80})
sns.lmplot(x="x", y="y", data=anscombe.query("dataset == 'II'"),ci=None, scatter_kws={"s": 80})
sns.lmplot(x="x", y="y", data=anscombe.query("dataset == 'II'"),order=2, ci=None, scatter_kws={"s": 80})
sns.lmplot(x="x", y="y", data=anscombe.query("dataset == 'III'"),ci=None, scatter_kws={"s": 80})
# robust=True 使用 robust迴歸
sns.lmplot(x="x", y="y", data=anscombe.query("dataset == 'III'"),robust=True, ci=None, scatter_kws={"s": 80})
tips["big_tip"] = (tips.tip / tips.total_bill) > .15
sns.lmplot(x="total_bill", y="big_tip", data=tips, y_jitter=.03)
# 使用邏輯迴歸
sns.lmplot(x="total_bill", y="big_tip", data=tips,logistic=True, y_jitter=.03)
# 非引數迴歸
sns.lmplot(x="total_bill", y="tip", data=tips,lowess=True)
2、regplot()
# 繪製殘差分佈
sns.residplot(x="x", y="y", data=anscombe.query("dataset == 'I'"),scatter_kws={"s": 80});
多變數關係
上面的圖表展示了許多探索一對變數之間關係的方法。很多時候,我們更關心兩個變數變化是如何影響第三個變數的。這也是lmplot()~與regplot()的區別之一。regplot()只能顯示一對變數之間的關係,而lmplot()結合了regplot()與FacetGrid,提供了一個簡單的介面,允許你探索最多其他三個分類變數的影響。
# 增加分類
sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips)
# 增加樣式
sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], palette="Set1")
# 橫向增加時間變數
sns.lmplot(x="total_bill", y="tip", hue="smoker", col="time", data=tips);
# 縱向增加性別變數
sns.lmplot(x="total_bill", y="tip", hue="smoker",col="time", row="sex", data=tips);
# 分兩行顯示 col_wrap=2
sns.lmplot(x="total_bill", y="tip", col="day",col_wrap=2,data=tips)