ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

Feature request: export `plot_theme()`

Open teunbrand opened this issue 3 months ago • 0 comments

I think it would be neat to have access to the function that completes a theme. By the time ggplot_build() is run, the theme isn't completed yet, and by the time ggplot_gtable() is run, the theme settings are lost. My primary use case would be in testing guide extensions: tweak a theme setting and test if it is applied correctly in the guide. I'd like to do roughly something like this, but this currently doesn't work because the theme isn't complete.

library(ggplot2)
p <- ggplot(mpg, aes(displ, hwy, colour = factor(cyl))) + geom_point()
build <- ggplot_build(p)

guides <- build$plot$guides
my_theme <- build$plot$theme

# Does not work
grob <- guides$assemble(my_theme + theme(legend.direction = "horizontal"))
#> Error in as.unit(e1): object is not coercible to a unit
# Do test on `grob`
grob <- guides$assemble(my_theme + theme(legend.direction = "vertical"))
#> Error in as.unit(e1): object is not coercible to a unit
# Do test on `grob`

To make this work, I'd have to use the unexported plot_theme() function.

my_theme <- theme(!!!ggplot2:::plot_theme(build$plot))
grob <- guides$assemble(my_theme + theme(legend.direction = "vertical"))
# Do test on `grob`
grob <- guides$assemble(my_theme + theme(legend.direction = "vertical"))
# Do test on `grob`

Created on 2024-03-25 with reprex v2.1.0

teunbrand avatar Mar 25 '24 11:03 teunbrand