【发布时间】:2019-09-15 06:09:38
【问题描述】:
每个人。我有一组我称之为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.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)")
我想创建一个与此代码生成的图表类似的图表,但以更简洁的方式。
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()
我将不胜感激任何帮助或指导,并提前感谢那些比我更精通 R 的人。
【问题讨论】:
-
这些是字符值。如果您希望它们成为实际的 R 公式,那么您可能需要使用 as.formula。
-
@42- 是否有必要使用
as.formula转换它们?有无我都试过了,都没有看到任何效果。 -
我真的不知道是否需要转换。 ggplot2语义有很多非标准的评估机制。