简体   繁体   中英

Plotting predicted probability of GLM in R with ggplot2

I want to create a plot containing multiple lines for different predicted probabilities of different land use categories from an average model.

I now have this code for two of the categories (in total I want to plot 4):

Cat1.res <- invlogit(av.model2022.hec$coefficients["full","(Intercept)"]
                     + av.model2022.hec$coefficients["full","Cat.1"]*seq(min(df2022hec$Cat.1), max(df2022hec$Cat.1),(max(df2022hec$Cat.1) - min(df2022hec$Cat.1))/50))

Cat9.res <- invlogit(av.model2022.hec$coefficients["full","(Intercept)"]
                     + av.model2022.hec$coefficients["full","Cat.9"]*seq(min(df2022hec$Cat.1), max(df2022hec$Cat.9),(max(df2022hec$Cat.9) - min(df2022hec$Cat.9))/50))

Cat1.seq <- seq(min(df2022hec$Cat.1), max(df2022hec$Cat.1),(max(df2022hec$Cat.1) - min(df2022hec$Cat.1))/50)

Cat9.seq <- seq(min(df2022hec$Cat.9), max(df2022hec$Cat.9),(max(df2022hec$Cat.9) - min(df2022hec$Cat.9))/50) 

plot(Cat9.seq, Cat9.res)
line(Cat1.seq, Cat1.res)

ggplot(df2022hec, aes(x=Cat9.seq, y=Cat9.res)) + 
  geom_line(aes(y = Cat1.res), color = "darkred") 

The first way of plotting, with the plot() function and line() function, works. However, ggplot2 has a lot more possibilities to make the plot look nice so I would prefer to use that. However, if I run the last bit of coding I get the following error:

Error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (1277): y and x
Backtrace:
 1. base `<fn>`(x)
 2. ggplot2:::print.ggplot(x)
 4. ggplot2:::ggplot_build.ggplot(x)
 5. ggplot2 by_layer(function(l, d) l$compute_aesthetics(d, plot))
 6. ggplot2 f(l = layers[[i]], d = data[[i]])
 7. l$compute_aesthetics(d, plot)
 8. ggplot2 f(..., self = self)
 9. ggplot2:::check_aesthetics(evaled, n)

So I guess I need to find a way to make the seq and res objects I created the same length as my data? Is that the only problem? And if so, how do I do that?

Thanks in advance!

啊,我想我已经通过将值 50 更改为值 1276 来解决它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM