我是R的新手,我的数据符合以下三个模型:
模型1:y = a(x)+ b
lm1 = lm(data$CBI ~ data$dNDVI)
模型2:y = a(x)2 + b(x)+ c
lm2 <- lm(CBI ~ dNDVI + I(dNDVI^2), data=data)
模型3:y = x(a | x | + b)-1
lm3 = nls(CBI ~ dNDVI*(a*abs(dNDVI) + b) - 1, start = c(a = 1.5, b = 2.7), data = data)
现在我想在R中绘制所有这三个模型,但我找不到办法,你能帮助我吗?我尝试了前两个模型如下,它工作,但我不知道如何添加模型3:
ggplot(data = data, aes(x = dNDVI, y = CBI)) +
geom_point() +
geom_smooth(method = lm, formula = y ~ x, size = 1, se = FALSE) +
geom_smooth(method = lm, formula = y ~ x + I(x^2), size = 1, se = FALSE ) +
theme_bw()
我还想添加一个图例,它同样显示3种不同颜色或类型的线条/曲线。你能指导我如何在图中做到吗?
答案 0 :(得分:1)
使用iris作为虚拟集来表示三个模型:
new.dat <- data.frame(Sepal.Length=seq(min(iris$Sepal.Length),
max(iris$Sepal.Length), length.out=50)) #new data.frame to predict the fitted values for each model
m1 <- lm(Petal.Length ~ Sepal.Length, iris)
m2 <- lm(Petal.Length ~ Sepal.Length + I(Sepal.Length^2), data=iris)
m3 <- nls(Petal.Length ~ Sepal.Length*(a*abs(Sepal.Length) + b) - 1,
start = c(a = 1.5, b = 2.7), data = iris)
new.dat$m1.fitted <- predict(m1, new.dat)
new.dat$m2.fitted <- predict(m2, new.dat)
new.dat$m3.fitted <- predict(m3, new.dat)
new.dat <- new.dat %>% gather(var, val, m1.fitted:m3.fitted) #stacked format of fitted data of three models (to automatically generate the legend in ggplot)
ggplot(new.dat, aes(Sepal.Length, val, colour=var)) +
geom_line()