有没有办法调整Cowplot对象的主题?

问题描述

我可以更改组合图的主题吗?

示例:

library(ggplot2)
library(cowplot)
p1 = ggplot(diamonds,aes(x = price)) + geom_histogram(bins = 30)
p2 = ggplot(diamonds,aes(x = table)) + geom_histogram(bins = 30)
p = cowplot::plot_grid(p1,p2)

这有效:

p1 + theme_bw()

这不起作用:

p + theme_bw()

解决方法

简短的回答是“否”。

您在牛图中看到的图已被渲染为grobs。它们没有可以更改的主题元素。从理论上讲,您可以“进入”埋在p结构内部的grob,并一次更改单个grob,但这是困难,凌乱且不可靠的。

作为展示技巧的技巧,这里是将p更改为theme_bw外观的方法:

p

enter image description here

p$layers <- lapply(p$layers,function(x) {
  y <- x$geom_params[[1]][[1]][[6]][[4]][[1]][[4]]
  y[[1]][[9]]$fill <- "white"
  y[[1]][[9]]$col <- "black"
  y[[4]][[7]]$col <- "gray90"
  y[[5]][[7]]$col <- "gray90"
  y[[2]][[7]]$col <- "gray90"
  y[[3]][[7]]$col <- "gray90"
  x$geom_params[[1]][[1]][[6]][[4]][[1]][[4]] <- y
  x
})

p

enter image description here