R 覆盖在散点图上的多个公式
各位。我有一组我称之为df_train的数据和各种感兴趣的回归公式。这是供您参考的:R 覆盖在散点图上的多个公式,r,ggplot2,R,Ggplot2,各位。我有一组我称之为df_train的数据和各种感兴趣的回归公式。这是供您参考的: df_train <- data.frame( x = c(0, 0.111111, 0.222222, 0.333333, 0.444444, 0.555556, 0.666667, 0.777778, 0.888889, 1), y = c(0.349486, 0.830839, 1.007332, 0.971507, 0.133066, 0.166823, -0.848307, -0.445
df_train <- data.frame(
x = c(0, 0.111111, 0.222222, 0.333333, 0.444444, 0.555556, 0.666667, 0.777778, 0.888889, 1),
y = c(0.349486, 0.830839, 1.007332, 0.971507, 0.133066, 0.166823, -0.848307, -0.445686, -0.563567, 0.261502))
forms <- c("y~1",
"y~x",
"y~poly(x, 2, raw=TRUE)",
"y~poly(x, 3, raw=TRUE)",
"y~poly(x, 4, raw=TRUE)",
"y~poly(x, 5, raw=TRUE)",
"y~poly(x, 6, raw=TRUE)",
"y~poly(x, 7, raw=TRUE)",
"y~poly(x, 8, raw=TRUE)",
"y~poly(x, 9, raw=TRUE)")
我将感谢任何帮助或指导,并提前感谢那些比我更精明的人 这是一种完全可复制的解决方案:
库(ggplot2)
图书馆(purrr)
这些都是字符值。如果希望它们是实际的R公式,则可能需要使用as.formula。@42-是否需要使用as.formula
转换它们?我尝试了有和没有,但没有看到任何效果。我真的不知道转换是必要的。ggplot2语义有很多非标准的评估机制。我还没有开发出直觉来判断何时需要purrr
映射工具。在这个问题上,什么使映射成为必要?我仍然不明白为什么我尝试的解决方案不起作用。我将数据放在长格式中,并将公式作为颜色变量,因此我尝试的解决方案确实不起作用吗?@StatGuy45可以用相应的lappy(…)
调用替换lappy(X=forms,FUN=function(t)geom_平滑(mapping=aes(color=paste)(“Model”),其中(X=(forms==t))),method=“lm”,se=FALSE,formula=t,size=0.5))
。我使用了map
,因为在我看来,你想要的是一个tidyverse
解决方案。@StatGuy45重点是你必须在列表中添加多个层。
。实际上我是从这里了解到这一点的:
df_train_exp <- df_train %>%
add_column(., forms = forms) %>%
expand(., x, forms) %>%
left_join(., df_train) %>%
select(., x, y, forms) %>%
group_by(., forms) %>%
arrange(., forms, x) %>%
ungroup(.)
ggplot(df_train_exp, aes(x = x, y = y)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, formula = forms[1], size = 0.5) +
geom_smooth(method = "lm", se = FALSE, formula = forms[2], size = 0.5) +
geom_smooth(method = "lm", se = FALSE, formula = forms[3], size = 0.5) +
geom_smooth(method = "lm", se = FALSE, formula = forms[4], size = 0.5) +
geom_smooth(method = "lm", se = FALSE, formula = forms[5], size = 0.5) +
geom_smooth(method = "lm", se = FALSE, formula = forms[6], size = 0.5) +
geom_smooth(method = "lm", se = FALSE, formula = forms[7], size = 0.5) +
geom_smooth(method = "lm", se = FALSE, formula = forms[8], size = 0.5) +
geom_smooth(method = "lm", se = FALSE, formula = forms[9], size = 0.5) +
theme_classic()
ggplot(df_train_exp, aes(x = x, y = y, color = forms)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, formula = forms, size = 0.5) +
theme_classic()