自动测试ggplot2中的所有主题

时间:2018-05-06 20:06:59

标签: r ggplot2

我可以使用库ggplot2ggthemes中的所有主题自动绘制相同的图表。到目前为止,我设法做到的唯一方法是(例如):

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

其中k可以由k <- theme_base()设置。也就是说,我可以列出主题,k是迭代此列表的变量。

然后,除了按主题添加主题作为列表的元素之外,创建此lits的经济实惠方式是什么。

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

这会查找以字符串开头的所有对象&#34;他们&#34;在ggplot2环境中:

 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"