如何在R中的同一图上绘制线性回归模型和泊松回归模型?

问题描述 投票:0回答:1

我正在处理一组简单的数据,这些数据涉及一头大象的年龄(解释性的)以及每头大象拥有多少成功的交配伙伴(响应)。我发现了两个模型:一个是线性回归模型,第二个是泊松回归模型。我想绘制交配与年龄的关系图,然后将这两个模型叠加到同一图上。然后,我将比较哪个在视觉上更合适。我一直在搞乱ggplot,只是常规的plot函数,还有一些行的东西。我真的不知道该怎么做。

提前感谢。

r plot regression linear-regression poisson
1个回答
0
投票

如果您只想可视化,那么使用predict(, type = "response")作为显示结果模型的方法非常容易。我对两个模型都使用glm,但从技术上讲,lm对于线性模型也适用:

set.seed(11)
# sample size
n <- 50
# regression coefficients
beta0 <- 0
beta1 <- 0.04
beta2 <- 0.05
# generate covariate values
x <- round(runif(n=n, min=1, max=40))
# compute mu's
mu <- exp(beta0 + beta1 * x + beta2^2 * x)
# generate Y-values
y <- rpois(n = n, lambda=mu)
# data set
data <- data.frame(matings=y, age=x)
data



fitLM <- glm(matings ~ age, data, family = gaussian(link = "identity"))
fitPOIS <- glm(matings ~ age, data, family = poisson(link = "log"))
AIC(fitLM, fitPOIS) # poisson has lower AIC

newdat <- data.frame(age = seq(1,40,0.1))
newdat$predLM <- predict(fitLM, newdata = newdat, type = "response")
newdat$predPOIS <- predict(fitPOIS, newdata = newdat, type = "response")

plot(matings ~ age, data)
lines(predLM ~ age, newdat, col = 2)
lines(predPOIS ~ age, newdat, col = 4)
legend("topleft", legend = c("lm", "poisson"), col = c(2,4), lty = 1)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.