Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select ggtheme randomly

I would like to draw a ggplot with a random theme (In fact, I want to draw many plots, each with a different theme). 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?

like image 396
Joachim Schork Avatar asked Feb 01 '19 12:02

Joachim Schork


3 Answers

Sample from the functions and not the names of the functions. Also, sample returns a list when sampling from anything more complex than a scalar, so you need the first list element. Eg:

> sample(c(sqrt, sqrt),2)
[[1]]
function (x)  .Primitive("sqrt")

[[2]]
function (x)  .Primitive("sqrt")

So get a random theme function with:

random_theme <- sample(c(theme_gray, theme_bw, theme_light, theme_dark, theme_minimal, theme_classic), 1)[[1]]

and call it when you plot:

ggplot(df, aes(x, y)) +geom_line() + random_theme()

Resample random_theme and plot again to update.

Also, you probably don't need the <<- which I guess is a hangover from desperately trying to make something work...

like image 59
Spacedman Avatar answered Nov 10 '22 20:11

Spacedman


You could do this with match.fun():

random_theme = match.fun(sample(c("theme_gray", "theme_bw", "theme_light", "theme_dark", "theme_minimal", "theme_classic"), 1))

ggplot(df, aes(x, y)) +
 geom_line() +
 random_theme()
like image 30
Fino Avatar answered Nov 10 '22 20:11

Fino


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)  , "()")))
like image 2
patL Avatar answered Nov 10 '22 20:11

patL