use*_*502 3 plot r poisson glm
数据:
df <- structure(list(x = c(9.5638945103927, 13.7767187698566, 6.0019477258207,
10.1897072092089, 15.4019854273531, 10.9746646056535, 12.9429073949468,
20.7513493525379, 18.5764146937149, 2.91302077116471, 13.6523222711501,
10.0920467755108), y = c(83.949498880077, 18.066881289085, 71.3052196358606,
39.8975644317452, 57.2933166677927, 87.8484256883889, 92.6818329896141,
49.8297961197214, 56.3650103496898, 14.7950650020996, 37.9271392096266,
50.4357237591891), z = c("a", "c", "e", "f", "b", "a", "b", "a",
"b", "a", "c", "d")), .Names = c("x", "y", "z"), row.names = c(NA,
-12L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)
我的模特:
mod <- glm(y ~ x + I(x^2) + z, family=quasipoisson, data = df)
summary(mod)
Run Code Online (Sandbox Code Playgroud)
我想绘制这样的事情:
ggplot(df, aes(x=x,y=y)) +
geom_point() +
stat_smooth(method="lm",se=FALSE,
formula=y~x+I(x^2),fill="transparent",
colour="black") +
stat_smooth(method="lm",geom="ribbon",
formula=y~x+I(x^2),fill="transparent",
colour="red",linetype="dashed",fullrange=TRUE) +
scale_x_continuous(limits=c(-2,35)) +
coord_cartesian(xlim=c(2,25),
ylim=range(pretty(df$y)))
Run Code Online (Sandbox Code Playgroud)

但是,我绘制的模型显然不是同一型号mod,没有z,它不是quasiposson.
我如何使用我的实际模型绘制ggplot之类的东西?predict不过我看过,当有多个解释时,我完全不知道该做什么,就像我的情况一样.我不在乎这样做ggplot2
看起来您可以通过使用来简单地使您的示例适应您的新模型stat_smooth(method='glm', family=quasipoisson, ...),但添加z到公式中会导致错误.从ggplot2文档中可以看出,predictdf这是用于生成间隔限制的内容.查看该函数的代码,看起来它只是用于处理x维度的预测.但是我们可以轻松编写我们自己的多维工作版本,然后将限制绘制为单独的图层.
mypredictdf <- function (model, newdata, level=0.95){
pred <- stats::predict(model, newdata = newdata, se =TRUE, type = "link")
std <- qnorm(level/2 + 0.5)
data.frame(newdata,
y = model$family$linkinv(as.vector(pred$fit)),
ymin = model$family$linkinv(as.vector(pred$fit - std * pred$se)),
ymax = model$family$linkinv(as.vector(pred$fit + std * pred$se)),
se = as.vector(pred$se))
}
px <- with(df, seq(from=min(x), to=max(x), length=100))
pdf <- expand.grid(x=px, z=unique(df$z))
pdf <- mypredictdf(mod, newdata=pdf)
g <- ggplot(data=pdf, aes(group=z))
g <- g + geom_point(data=df, aes(x=x, y=y, color=z))
g <- g + geom_ribbon(aes(x=x, ymin=ymin, ymax=ymax),
alpha=0.2)
g <- g + geom_line(aes(x=x, y=y, color=z))
Run Code Online (Sandbox Code Playgroud)

看起来好像是一个好主意:
g <- g + facet_wrap(~z)
Run Code Online (Sandbox Code Playgroud)
