An S3 plot theme can be utilized to apply a theme to several plots through a custom user function as follows:
ggplot2
function and returns a modified ggplot2
object with the desired theme. For example:my_theme <- function(...) {
ggplot2::ggplot(...) +
ggplot2::theme_minimal() +
ggplot2::theme(legend.position = "bottom")
}
class(my_theme) <- c("my_theme", "ggplot")
ggplot2::ggplot_build
and ggplot2::ggplot_gtable
functions, and return the modified plot object with the theme applied. For example:apply_theme <- function(plot) {
plot_data <- ggplot2::ggplot_build(plot)
plot_table <- ggplot2::ggplot_gtable(plot_data)
plot_table$add_theme(my_theme())
grid::grid.draw(plot_table)
plot
}
plot1 <- ggplot2::ggplot(mtcars, aes(mpg, wt)) + geom_point()
plot2 <- ggplot2::ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) + geom_point()
plot1_with_theme <- apply_theme(plot1)
plot2_with_theme <- apply_theme(plot2)
This will apply the my_theme
plot theme to plot1
and plot2
, and return modified plot objects with the theme applied.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-04-28 11:00:00 +0000
Seen: 8 times
Last updated: Mar 21 '23
How can one ensure that sub-classes have uniform method parameters in TypeScript?
How can the calculation of matrix determinant be performed using CUDA?
How can code repetition be prevented when using (box)plot functions?
When I attempt to generate a database, why does the azure-cosmos-emulator become unresponsive?
What steps can I take to prevent my webpage from slowing down when all parts of a div are displayed?