Search code examples
ggplot2plotgam

Gratia package: probability instead of log odds for plotting generalized additive model (GAM)


I was trying to plot a logistic GAM model using the gratia package (since it uses ggplot2), however I would like the effects (or partial effects) to be plotted in terms of probabilities instead of log odds.

I have tried by hand using probabilities, however I prefer to use the gratia package. Would there be a way to plot the probabilities specifically using the package?

The model (I created some data):

set.seed(1)
Perf1 <- rlnorm(100)
Sex <- sample(c(rep(1, 40), rep(0, 60)))
set.seed(2)
Group <- sample(c(rep(1, 30), rep(0, 70)))
set.seed(3)
Perf2 <- rlnorm(200)
G <- sample(c(rep(1, 20), rep(0, 80)))
Age <- sample(c(rep(7, 15), rep(8, 20), rep(9, 30), rep(10, 10), rep(11, 15), rep(12, 10)))



sample_data <-data.frame(Age = Age,
                         Sex = Sex,
                         G = G,
                         Group = Group,
                         Perf1 = Perf1,
                         Perf2 = Perf1
)

gam_fit <- gam(Group ~ Age + Sex + G + s(Perf1, k = 20) +
      s(Perf2, k = 20),
    data = sample_data, 
    family = "binomial",
    method="REML", select = F)

draw(gam_fit, parametric = T)

Plotting using gratia:

gam_fit

The effect or partial effect is on the log odds scale, while I would like probabilities instead, but I am unsure how to achieve this.


Solution

  • You'll have to add the model constant term and transform by the inverse of the link function:

    draw(gam_fit, constant = coef(gam_fit)[1], fun = inv_link(gam_fit))
    

    (and I'm not sure if constant or fun work on the parametric terms just now.)