r - `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
。)
解决方案
您可以将绘图元素列表添加到 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) +
推荐阅读
- javascript - 将 DIV 映射到 Vimeo/Youtube 时间戳
- colors - 根据乌龟自己的变量更改 NetLogo 中代理的颜色
- gulp - local web server can't see folder on level up entry point
- javascript - Call child method class in parent with parent instance
- python - Celery 任务时间什么时候开始计算?
- cmd - 命令提示符自动写入日志文件
- c - Error when passing multidimensional char array to a void function in C
- python - 处理数据框 pandas 中的数据
- mysql - 更新记录时如何避免mysql中的这个错误?
- apache - Force trailing slash if the URL exists