實現功能:
在散點圖上添加趨勢線(線性拟合線)反映兩個變量是正相關、負相關或者無相關關系。
實現代碼:
|
1 |
import pandas as pd |
|
2 |
import matplotlib as mpl |
|
3 |
import matplotlib.pyplot as plt |
|
4 |
import seaborn as sns |
|
5 |
import warnings |
|
6 |
warnings.filterwarnings(action='once') |
|
7 |
plt.style.use('seaborn-whitegrid') |
|
8 |
sns.set_style("whitegrid") |
|
9 |
print(mpl.__version__) |
|
10 |
print(sns.__version__) |
|
11 | |
|
12 |
def draw_scatter(file): |
|
13 |
# Import Data |
|
14 |
df = pd.read_csv(file) |
|
15 |
df_select = df.loc[df.cyl.isin([4, 8]), :] |
|
16 | |
|
17 |
# Plot |
|
18 |
gridobj = sns.lmplot( |
|
19 |
x="displ", |
|
20 |
y="hwy", |
|
21 |
hue="cyl", |
|
22 |
data=df_select, |
|
23 |
height=7, |
|
24 |
aspect=1.6, |
|
25 |
palette='Set1', |
|
26 |
scatter_kws=dict(s=60, linewidths=.7, edgecolors='black')) |
|
27 | |
|
28 |
# Decorations |
|
29 |
sns.set(style="whitegrid", font_scale=1.5) |
|
30 |
gridobj.set(xlim=(0.5, 7.5), ylim=(10, 50)) |
|
31 |
gridobj.fig.set_size_inches(10, 6) |
|
32 |
plt.tight_layout() |
|
33 |
plt.title("Scatterplot with line of best fit grouped by number of cylinders") |
|
34 |
plt.show() |
|
35 | |
|
36 |
draw_scatter("F:\數據雜壇\datasets\mpg_ggplot2.csv") |
實現效果:
在散點圖上添加趨勢線(線性拟合線)反映兩個變量是正相關、負相關或者無相關關系。紅藍兩組數據分别繪制出最佳的線性拟合線。

喜歡記得點贊,在看,收藏,
關注V訂閱号:數據雜壇,獲取數據集,完整代碼和效果,将持續更新!
,更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!