Search code examples
rggplot2gammgcv

Time (hours) formatting when plotting GAM smooth effects with mgcViz


I have a GAM model where time of day is one of the predictor values. Time is in numeric format, since as far as I understand, mgcv::gam doesn't accept POSIXct class. The model works fine, but I'd like to see a plot where smooth effect has HH:MM on the X-axis, instead of the continuous UNIX epoch. I'm using mgcViz for plotting.

How could I get nice time formats (HH/HH:MM) on the X-axis labels?

Reproducible example:

require(mgcv)
require(mgcViz)

min_datetime <- as.POSIXct(strptime("2021-12-27 06:00:00", "%Y-%m-%d %H:%M:%S"))
max_datetime <- as.POSIXct(strptime("2021-12-27 18:00:00", "%Y-%m-%d %H:%M:%S"))

x <- runif(100)
y <- runif(100)
tod <- runif(100, min = as.numeric(min_datetime), max = as.numeric(max_datetime))

df <- data.frame(x, y, tod)

mod <- gam(y ~ x + tod, data = df)

viz_mod <- getViz(mod)

plot_mod <- plot(viz_mod, select = 2) +
  l_fitLine(linetype = 1)

# Epoch on X-axis, should be HH:MM
print(plot_mod)

Solution

  • Since mgcViz is a wrapper around ggplot2, you can use standard ggplot2::scale_... functions to manipulate your labels, breaks, or anything else you want in the plot. Here we can use scale_x_continuous to convert the numeric x axis back to POSIXct and then format it as you desire.

    plot_mod +
      scale_x_continuous(labels = ~ format(as.POSIXct(.x, origin = origin), "%H:%M"))
    

    enter image description here