Skip to content

Feature request: export plot_theme() #5801

Closed
@teunbrand

Description

@teunbrand

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions