公式中带有变次多项式的“geom_smooth”

pas*_*y51 3 r ggplot2

我有以下ggplot2代码,可以绘制不同程度的多个多项式拟合:

library(ggplot2)

set.seed(1234)
n = 400
x = rnorm(n, sd=0.4)
y = -x + 2*x^2 - 3*x^3 + rnorm(n,sd=0.75)
df = data.frame(x=x,y=y)

deg = c(1,2,3,10)
cols = c("red","green","blue","orange")
ggplot(df, aes(x=x,y=y)) + 
  geom_point() + 
  geom_smooth(method = "lm", formula= y~poly(x,deg[1]), se=F, col=cols[1]) +
  geom_smooth(method = "lm", formula= y~poly(x,deg[2]), se=F, col=cols[2]) +
  geom_smooth(method = "lm", formula= y~poly(x,deg[3]), se=F, col=cols[3]) +
  geom_smooth(method = "lm", formula= y~poly(x,deg[4]), se=F, col=cols[4]) 

Run Code Online (Sandbox Code Playgroud)

我想避免geom_smooth在每个学位上都重复这条线。但我不知道如何geom_smooth理解通过变量传递的动态程度。对于上述问题有更优雅的解决方案吗?如果能够自动更改颜色而不需要显式传递cols向量,那就太好了。(默认配色方案就可以)。

我尝试as.formula(paste0("y~poly(x,",deg[i],")"))通过循环使用,但运气不佳(循环似乎不是正确的方法ggplot。)

eip*_*i10 6

您可以将绘图元素列表添加到 ggplot 中,这样您就可以用来map创建四个调用的列表geom_smooth,每个调用对应deg.

library(tidyverse)

ggplot(df, aes(x=x,y=y)) + 
  geom_point() +
  map(1:length(deg), 
      ~geom_smooth(method="lm", formula=y~poly(x, deg[.x]), se=F, col=cols[.x]))
Run Code Online (Sandbox Code Playgroud)

如果您愿意,您还可以添加图例。例如:

ggplot(df, aes(x=x,y=y)) + 
  geom_point(colour="grey60") +
  map(1:length(deg), 
      ~geom_smooth(method="lm", formula=y~poly(x, deg[.x]), se=F,
                   aes(color=factor(deg[.x])))) + 
  scale_colour_manual(name="Degree", breaks=deg, values=set_names(cols, deg)) +
  theme_bw() +
  theme(legend.text.align=1)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果您对默认颜色感到满意,请将行更改scale_colour_manual为:

scale_colour_discrete(name="Degree", breaks=deg) +
Run Code Online (Sandbox Code Playgroud)