Select ggtheme randomly

  • A+

I would like to draw a ggplot with a random theme (In fact, I want to draw many plots, each with a different themes). Consider the following reproducible example:

# Exmple data df <- data.frame(x = 1:10, y = 1:10)  # Select theme randomly random_theme <<- sample(c("theme_gray", "theme_bw", "theme_light", "theme_dark", "theme_minimal", "theme_classic"), 1)  # Draw ggplot ggplot(df, aes(x, y)) +   geom_line() +   random_theme            # This line does not work 

Question: How can I select a ggtheme randomly?


Sice your random_theme is a character vector, you can use eval and then parse to parse your theme.

library(tidyverse)  ggplot(df, aes(x, y)) +   geom_line() +   eval(parse(text = paste0(random_theme, "()"))) 

Or more directly:

ggplot(df, aes(x, y)) +   geom_line() +   eval(parse(text = paste0(sample(c("theme_gray",                                     "theme_bw",                                      "theme_light",                                      "theme_dark",                                      "theme_minimal",                                      "theme_classic"), 1)  , "()"))) 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: