2 散點圖Scatterplot(代碼下載)
散點圖能夠顯示2個維度上2組數據的值。每個點代表一個觀察點。X(水平)和Y(垂直)軸上的位置表示變量的值。研究這兩個變量之間的關係是非常有用的。在seaborn中通過regplot和lmplot製作散點圖,regplot和lmplot核心功能相近,regplot相對簡單點,如果要定製圖像更深層次功能,需要使用lmplot。此外也用Pairplot製作多變量圖。該章節主要內容有:
- 基礎散點圖繪製 Basic scatterplot
- 更改標記參數 Control marker features
- 自定義線性迴歸擬合 Custom linear regression fit
- 使用分類變量爲散點圖着色 Use categorical variable to color scatterplot
- 座標軸範圍設置 Control axis limits of plot
- 在散點圖上添加文本註釋 Add text annotation on scatterplot
- 自定義相關圖 Custom correlogram
#調用seaborn
import seaborn as sns
#調用seaborn自帶數據集
df = sns.load_dataset('iris')
#顯示數據集
df.head()
sepal_length | sepal_width | petal_length | petal_width | species | |
---|---|---|---|---|---|
0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa |
1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa |
2 | 4.7 | 3.2 | 1.3 | 0.2 | setosa |
3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa |
4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa |
1.基礎散點圖繪製 Basic scatterplot
# 使用regplot()函數製作散點圖。您必須提供至少2個列表:X軸和Y軸上的點的位置。
# 默認情況下繪製線性迴歸擬合直線,可以使用fit_reg = False將其刪除
# use the function regplot to make a scatterplot 有迴歸曲線
# scipy<1.2會有warning
sns.regplot(x=df["sepal_length"], y=df["sepal_width"]);
# Without regression fit 無迴歸曲線
sns.regplot(x=df["sepal_length"], y=df["sepal_width"], fit_reg=False);
2. 更改標記參數 Control marker features
# 可以散點圖自定義顏色,透明度,形狀和大小
# Change shape of marker控制散點的形狀
sns.regplot(x=df["sepal_length"], y=df["sepal_width"], marker="+", fit_reg=False);
# List of available shapes 可用的形狀查看
import matplotlib
all_shapes=matplotlib.markers.MarkerStyle.markers.keys()
all_shapes
dict_keys(['.', ',', 'o', 'v', '^', '<', '>', '1', '2', '3', '4', '8', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_', 'P', 'X', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 'None', None, ' ', ''])
# More marker customization,更具scatter_kws參數控制顏色,透明度,點的大小
sns.regplot(x=df["sepal_length"], y=df["sepal_width"], fit_reg=False, scatter_kws={"color":"darkred","alpha":0.3,"s":20});
3. 自定義線性迴歸擬合 Custom linear regression fit
# 您可以自定義seaborn提出的迴歸擬合的外觀。在此示例中,顏色,透明度和寬度通過line_kws = {}選項進行控制。
sns.regplot(x=df["sepal_length"], y=df["sepal_width"], line_kws={"color":"r","alpha":0.7,"lw":5});
4. 使用分類變量爲散點圖着色 Use categorical variable to color scatterplot
- 每組映射一種顏色 Map a color per group
- 每組映射一個標記 Map a marker per group
- 使用其他調色板 Use another palette
- 控制每組的顏色 Control color of each group
# 每組映射一種顏色 Map a color per group
# Use the 'hue' argument to provide a factor variable hue設置species不同種類的的顏色
sns.lmplot( x="sepal_length", y="sepal_width", data=df, fit_reg=False, hue='species', legend=False);
# Move the legend to an empty part of the plot 需要通過matplotlib更改legend的位置
import matplotlib.pyplot as plt
plt.legend(loc='best');
# 每組映射一個標記 Map a marker per group
# give a list to the marker argument 通過hue設定顏色,markes設定各點的形狀
sns.lmplot( x="sepal_length", y="sepal_width", data=df, fit_reg=False, hue='species', legend=False, markers=["o", "x", "1"])
# Move the legend to an empty part of the plot
plt.legend(loc='lower right');
# 使用其他調色板 Use another palette
# Use the 'palette' argument 不同種類設定不同的顏色,顏色類型使用palette設定調色板顏色
sns.lmplot( x="sepal_length", y="sepal_width", data=df, fit_reg=False, hue='species', legend=False, palette="Set2")
# Move the legend to an empty part of the plot
plt.legend(loc='lower right');
# 控制每組的顏色 Control color of each group
# Provide a dictionary to the palette argument 調色盤使用自定義顏色
dict_color=dict(setosa="#9b59b6", virginica="#3498db", versicolor="#95a5a6")
sns.lmplot( x="sepal_length", y="sepal_width", data=df, fit_reg=False, hue='species', legend=False, palette=dict_color)
# Move the legend to an empty part of the plot
plt.legend(loc='lower right');
5. 座標軸範圍設置 Control axis limits of plot
# basic scatterplot
sns.lmplot( x="sepal_length", y="sepal_width", data=df, fit_reg=False)
# control x and y limits 設置軸的範圍,不過需要調用matplotlib.pyplot 模塊,通常都是matplotlib和seaborn一起用
plt.ylim(0, 20)
plt.xlim(0, None)
(0, 8.122715679666298)
6. 在散點圖上添加文本註釋 Add text annotation on scatterplot
- 添加一個註釋 Add one annotation
- 添加多個註釋 Use a loop to annotate each marker
# 添加一個註釋 Add one annotation
import pandas as pd
# 製作數據集
df_test = pd.DataFrame({
'x': [1, 1.5, 3, 4, 5],
'y': [5, 15, 5, 10, 2],
'group': ['A','other group','B','C','D']})
# 畫散點圖
p1=sns.regplot(data=df_test, x="x", y="y", fit_reg=False, marker="o", color="skyblue", scatter_kws={'s':400});
# 添加註釋
p1.text(3+0.2, 4.5, "An annotation", horizontalalignment='left', size='medium', color='black', weight='semibold')
Text(3.2, 4.5, 'An annotation')
# 添加多個註釋 Use a loop to annotate each marker
# basic plot
p1=sns.regplot(data=df_test, x="x", y="y", fit_reg=False, marker="o", color="skyblue", scatter_kws={'s':400})
# add annotations one by one with a loop
for line in range(0,df_test.shape[0]):
p1.text(df_test.x[line]+0.2, df_test.y[line], df_test.group[line], horizontalalignment='left', size='medium', color='black', weight='semibold')
7. 自定義相關圖 Custom correlogram
- 有迴歸方程的散點相關圖 correlogram with regression
- 無迴歸方程的散點相關圖 correlogram without regression
- 在相關圖上表示組 Represent groups on correlogram
- 相關圖子圖設置 Kind of plot for the diagonal subplots
- 子圖參數設置 parameters adjustment of subplots
# 有迴歸方程的散點相關圖 correlogram with regression
# library & dataset
import matplotlib.pyplot as plt
import seaborn as sns
df = sns.load_dataset('iris')
# with regression 有迴歸方程的散點相關圖
# 正對角線上的圖表示數據頻次的直方圖,其他表示散點圖
sns.pairplot(df, kind="reg");
# 無迴歸方程的散點相關圖 correlogram without regression
sns.pairplot(df, kind="scatter");
# 在相關圖上表示組 Represent groups on correlogram
# 通過hue設定種類,markers不同種類的點的表示方式
# 對角線爲核密度圖
sns.pairplot(df, kind="scatter", hue="species", markers=["o", "s", "D"], palette="Set2")
<seaborn.axisgrid.PairGrid at 0x21cc5179710>
# 在相關圖上表示組 Represent groups on correlogram
# you can give other arguments with plot_kws plot_kws更改散點圖的參數
sns.pairplot(df, kind="scatter", hue="species",plot_kws=dict(s=80, edgecolor="white", linewidth=3));
# 相關圖子圖設置 Kind of plot for the diagonal subplots
# diag_kind有auto,hist,kde選項,hist爲直方圖,kde爲散點圖
sns.pairplot(df, diag_kind="hist");
# 子圖參數設置 parameters adjustment of subplots
# You can custom it as a density plot or histogram so see the related sections 通過diag_kws調整子圖參數
sns.pairplot(df, diag_kind="kde", diag_kws=dict(shade=True, bw=.05, vertical=False));