Search code examples
rvisualizationgammgcv

How to rename x-axis labels in gam plot in R?


I fitted the model using the following code

mod1 <- gam(severity ~  s(mean_rh, k = 8) + s(mean_temp, k = 10) + s(mean_ws, k =7) + s(avg_daily_rain, k = 7), family = betar(),  data = dat_seasonal)

Here is the code used in producing plot

plot(mod1, pages = 1, all.terms = TRUE, rug = TRUE, residuals = TRUE, pch = 1, cex = 1, shade = TRUE, seWithMean = TRUE, shift = coef(mod1)[1])

I wanted to rename x-axis labels by renaming column names in the original data frame, using new name = old syntax, Mean temperature = mean_temp, Mean wind speed = mean_ws, Mean relative humidity = mean_rh, Mean rain per rainy day = avg_daily_rain

Here is my code

names(dat_seasonal) <- c("disease_severity", "Mean relative humidity", "Mean temperature", "Mean wind speed", "Mean rain per rainy day")

mod1 <- gam(disease_severity ~  s(`Mean relative humidity`, k = 8) + s(`Mean temperature`, k = 10) + s(`Mean wind speed`, k =7) + s(`Mean rain per rainy day`, k = 7), family = betar(),  data = dat_seasonal_gam)

summary(mod1)


plot(mod1, pages = 1, all.terms = TRUE, rug = TRUE, residuals = TRUE, pch = 1, cex = 1, shade = TRUE, seWithMean = TRUE, shift = coef(mod1)[1])

I am getting the following error message

Error in str2lang(termtext) : <text>:1:6: unexpected symbol
1: Mean relative
         ^

Apparently, the error message suggests that there should not be any spaces in the new names. Any leads on how to fix this? Thanks

NOTE: I can rename a single term using the following code, but there is no way rename all predictors at once.

plot(mod1, select = 4, xlab = "Mean rain per rainy day (mm)", rug = TRUE, residuals = TRUE, pch = 1, cex = 1, shade = TRUE, seWithMean = TRUE, shift = coef(mod1)[1])

Solution

  • Ended up using gratia package to rename individual figures and then combine them using patchwork package.

    p1 <- draw(mod1, select = "s(mean_rh)") +
          labs(x= "Mean relative humidity (%)", title = "")
    
    p2 <- draw(mod1, select = "s(mean_temp)") +
       labs(x= "Mean temperature (°C)", title = "") 
    
    p3 <- draw(mod1, select = "s(mean_ws)") +
      labs(x= "Mean wind speed (m/s)", title = "") 
    
    p4 <- draw(mod1, select = "s(avg_daily_rain)") +
      labs(x= "Mean rain per rainy day (mm)", title = "") 
    
    p1 + p2 + p3 + p4 + plot_layout(ncol = 2, nrow = 2)