Gilgamesh
Gilgamesh

Reputation: 629

Automate testing all the themes in ggplot2

I would a way to automate plotting the same graph with all the themes available in the libraries ggplot2 and ggthemes. Until now, the only way I've managed to do that is by (e.g):

qplot(data = mtcars, x = mtcars$mpg, y = mtcars$hp) + k

Where k could be set by k <- theme_base().That being said, I could make a list of themes and k being the variable that iterates over this list.

Then, what is an affordable way of creating this lits, besides adding theme by theme as an element of the list.

Upvotes: 0

Views: 530

Answers (2)

user9749982
user9749982

Reputation: 56

library(ggplot2)
# dput(ls(pattern = "theme",package:ggplot2))
defaults <- c("theme_bw", "theme_classic", "theme_dark", 
              "theme_grey", "theme_light", "theme_linedraw", 
              "theme_minimal", "theme_void")
library(ggthemes)
# dput(ls(pattern = "theme",package:ggthemes))
addons <- c("theme_base", "theme_calc", "theme_economist", 
            "theme_economist_white", "theme_excel", "theme_few", "theme_fivethirtyeight", 
            "theme_foundation", "theme_gdocs", "theme_hc", "theme_igray", 
            "theme_map", "theme_pander", "theme_par", "theme_solarized", 
            "theme_solarized_2", "theme_solid", "theme_stata", "theme_tufte", 
            "theme_wsj")

p <- ggplot(mtcars) + facet_wrap(~vs) +
  stat_qq(aes(sample = mpg, colour = factor(cyl)), geom="line")

pl1 <- lapply(defaults, function(th) p + get(th)() + ggtitle(th))
pl2 <- lapply(addons, function(th) p + get(th)() + ggtitle(th))

library(gridExtra)
library(Cairo)
CairoPDF("all_themes.pdf", width=8, height=32)
grid.arrange(arrangeGrob(grobs=pl1, top = "Original themes", ncol=2),
             arrangeGrob(grobs=pl2[-c(17:18)], top = "Third-party themes", ncol=2), heights=c(0.4, 1))
dev.off()

enter image description here enter image description here

Upvotes: 4

IRTFM
IRTFM

Reputation: 263451

This looks up all the objects that begin with the string "them" in the ggplot2 environment:

 thems <- ls(patt="^them", envir=environment(ggplot) )
 thems
 #   -----
 [1] "theme"          "theme_bw"       "theme_classic"  "theme_dark"     "theme_env"      "theme_get"     
 [7] "theme_gray"     "theme_grey"     "theme_light"    "theme_linedraw" "theme_minimal"  "theme_replace" 
[13] "theme_set"      "theme_update"   "theme_void"    

Upvotes: 2

Related Questions