如何在 R 中使用 ggplot2 创建的 abline 更改颜色?


要更改使用 ggplot2 在 R 中创建的 abline 颜色,我们可以按照以下步骤操作:

  • 首先,创建一个数据框。

  • 然后,使用 ggplot2 使用给定的斜率和截距创建回归线。

  • 之后,使用 color 参数创建相同的图形以更改 abline 颜色。

示例

创建数据框

让我们创建一个如下所示的数据框:

Open Compiler
x<-rnorm(25) y<-rnorm(25) df<-data.frame(x,y) df

输出

执行上述脚本后,会生成以下输出(由于随机化,此输出将在您的系统上有所不同):

        x            y
1   -0.51902492 -0.79354642
2   -0.42864943 -0.25896843
3    0.57382031  0.95552909
4   -1.68136435  0.19044111
5   -0.69830456 -0.01767888
6   -0.76028497 -0.19016998
7   -0.16044373  0.30392163
8   -1.30390581  0.00911881
9   -0.92685295 -0.63172007
10   2.05518766 -0.70310776
11   0.40343320  1.14764580
12  -1.01411102  0.29829312
13  -0.39075157  0.06896220
14   1.71747493  0.18522334
15   0.73520133 -0.01642746
16   0.19556420  0.55860325
17  -1.45367281  0.01375643
18  -2.42102756  0.63214669
19   0.16466908 -1.25939472
20  -0.88376161 -1.02222998
21  -0.68787689 -0.85754925
22  -0.33156054  0.38232947
23   0.14147640 -0.04030800
24   0.39239316 -0.46167568
25  -0.09390706 -0.27455582

创建回归线图

使用 ggplot2 使用给定的斜率和截距创建回归线,如下所示:

x<-rnorm(25) y<-rnorm(25) df<-data.frame(x,y) library(ggplot2) ggplot(df,aes(x,y))+geom_point()+geom_abline(slope=-0.062712, intercept=0.165886)

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

使用不同的线条颜色创建回归线图

使用 ggplot2 使用给定的斜率和截距创建具有不同线条颜色的回归线,如下所示:

x<-rnorm(25) y<-rnorm(25) df<-data.frame(x,y) library(ggplot2) ggplot(df,aes(x,y))+geom_point()+geom_abline(slope=-0.062712, intercept=0.165886,colour="green")

输出

更新于: 2021年11月11日

2K+ 浏览量

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告