首页 > 解决方案 > `geom_smooth` 在公式中具有可变次数多项式

问题描述

我有以下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]) 

我想避免geom_smooth为每个学位重复这条线。但我不知道如何geom_smooth理解通过变量传递的动态程度。有没有更优雅的解决方案?如果不需要显式传递cols向量,也可以自动更改颜色。(默认配色方案很好)。

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

标签: rggplot2

解决方案


您可以将绘图元素列表添加到 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]))

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

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)

在此处输入图像描述

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

scale_colour_discrete(name="Degree", breaks=deg) +

推荐阅读