实现功能:
在散点图上添加趋势线(线性拟合线)反映两个变量是正相关、负相关或者无相关关系。
实现代码:
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订阅号:数据杂坛,获取数据集,完整代码和效果,将持续更新!
| 留言与评论(共有 0 条评论) “” |