rggplot2gamgratia

Changing the title and labels of the plot provided by draw in the gratia package


I would like to change the title of the plot and the labels on the x and y axes without modifying the variable names in the dataframe.

I am using the gratia package.

library(patchwork)
library(gratia)  

set.seed(123)
data <- data.frame(
  y = rnorm(100),    
  x1 = rnorm(100),   
  x2 = rnorm(100)    
)

model <- gam(y ~ s(x1) + s(x2), data = data)
smooth_plot <- draw(model, ci_col = "steelblue", smooth_col = "blue", grouped_by = TRUE) 
smooth_plot <- smooth_plot + plot_layout(nrow = 1, ncol = 2)

print(smooth_plot)

In this case, I would like 'x1' to be replaced with 'Number of people having a vegetarian diet', 's(x1)' to be replaced with 's(Number of people having a vegetarian diet)', 'x2' to be replaced with 'Iron levels in the blood', and 's(x2)' to be replaced with 's(Iron levels in the blood).

This is only an fictious example for a more complex model and work.


Solution

  • A simple option would be to draw the plots separately which allows to set the plot and axis title using labs() and combining them afterwards using e.g. patchwork::wrap_plots:

    library(ggplot2)
    library(patchwork)
    library(gratia)
    library(mgcv)
    
    p1 <- draw(model,
      ci_col = "steelblue",
      smooth_col = "blue", grouped_by = TRUE,
      select = "s(x1)"
    ) +
      labs(
        x = "Number of people having a vegetarian diet",
        title = "s(Number of people having a vegetarian diet)"
      )
    
    p2 <- draw(model,
      ci_col = "steelblue",
      smooth_col = "blue", grouped_by = TRUE,
      select = "s(x2)"
    ) +
      labs(
        x = "Iron levels in the blood",
        title = "s(Iron levels in the blood)"
      )
    
    list(p1, p2) |>
      wrap_plots() +
      plot_layout(nrow = 1, ncol = 2)