简体   繁体   English

`geom_smooth` 在公式中具有可变次数多项式

[英]`geom_smooth` with variable degree polynomial in the formula

I have the following ggplot2 code that plots multiple polynomial fits with various degrees:我有以下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]) 

I would like to avoid repeating the geom_smooth line for every degree.我想避免为每个度数重复geom_smooth线。 But I can't figure out how to get geom_smooth to understand a dynamic degree passed through a variable.但我不知道如何让geom_smooth理解通过变量传递的动态度数。 Is there a more elegant solution to the above?有没有更优雅的解决方案? It would be nice to also automatically change the colors without the need to explicitly pass the cols vector.如果不需要显式传递cols向量,也可以自动更改颜色。 (Default color scheme is fine). (默认配色方案很好)。

I have tried to use as.formula(paste0("y~poly(x,",deg[i],")")) through a loop without much luck (and loops don't seem to be the right approach with ggplot .)我试图通过as.formula(paste0("y~poly(x,",deg[i],")"))使用as.formula(paste0("y~poly(x,",deg[i],")")) ,但运气不佳(循环似乎不是ggplot的正确方法.)

You can add a list of plot elements to a ggplot, so you could use map to create a list of four geom_smooth calls, one for each degree in deg .您可以将绘图元素列表添加到 ggplot,因此您可以使用map创建四个geom_smooth调用的列表, 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]))

You can also add a legend if you wish.如果您愿意,还可以添加图例。 For example:例如:

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)

在此处输入图片说明

If you're happy with the default colours, change the scale_colour_manual line to:如果您对默认颜色感到满意,请将scale_colour_manual行更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM