gavinsimpson / gratia

ggplot-based graphics and useful functions for GAMs fitted using the mgcv package
https://gavinsimpson.github.io/gratia/
Other
206 stars 28 forks source link

legend in draw() #174

Closed BivGEV closed 2 years ago

BivGEV commented 2 years ago

Is it possible to edit the legend labels in the draw() function? Thanks

gavinsimpson commented 2 years ago

Do you mean for the colour bars used for the surface plots or something else? (draw() is a generic function so you could be asking about one of several functions.)

Modifying the guide() should work (with a message, possibly) for the colour bars:

library("gratia")
library("mgcv")
library("ggplot2")
# simulate some data
df <- data_sim("eg2", n = 1000, dist = "normal", scale = 1, seed = 2)
m <- gam(y ~ s(x, z, k = 40), data = df, method = "REML")
draw(m) & guides(fill = guide_colourbar(title = "my label"))

But that's only going to work for plots of single smooths owing to how the plots are wrapped in a patchwork.

Ultimately, plotting by hand the objects {gratia} works with is usually the best option if you want total control. In this case, for that you want sm <- smooth_estimates(m) to get the required information about the smooth(s) in model m and then you can plot exactly as you would like:

sm <- smooth_estimates(m)
draw(sm) + guides(fill = guide_colourbar(title = "my label"))

or even fully in control by plotting everything yourself

ggplot(sm, aes(x = x, y = z, fill = est)) +
  geom_raster() +
  geom_contour(aes(z = est, fill = NULL)) +
  labs(fill = "my label") +
  scale_fill_viridis_c()

I'm not 100% sure why labs() won't work with the draw() options - probably because I set the title for the colour bar there using the guides() method.

If you are thinking of other outputs, please provide more details of what you are trying to do so I can address that specifically.

gavinsimpson commented 2 years ago

Closing as no feedback from the @BivGEV. I'll reopen if further explanation is provided.