根据方面的存在有条件地修改ggplot主题?

mfh*_*man 8 r ggplot2

我正在研究自定义 ggplot2 主题,并认为根据绘图对象的某些特征自动修改主题元素可能很不错。例如,有没有办法指定如果绘图包含面,则为每个面板添加边框?

我想问题是真的,我可以从自定义 theme() 调用中访问当前的 gg 对象,然后有条件地应用某些主题元素吗?在我的脑海中,我会将我的主题功能定义为这样的:

theme_custom <- function() {
  if (plot$facet$params > 0) {
  theme_minimal() +
    theme(panel.border = element_rect(color = "gray 50", fill = NA))
  }
  else {
    theme_minimal()
    }
}
Run Code Online (Sandbox Code Playgroud)

如果这是可能的,它在使用中看起来像这样:

library(ggplot2)

# plot with facets automatically adds panel borders
ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  facet_wrap(vars(cyl)) +
  theme_custom()
Run Code Online (Sandbox Code Playgroud)

# plot without facets no panel border
ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  theme_custom() 
Run Code Online (Sandbox Code Playgroud)

注意:这最初发布在RStudio 社区上,但没有收到答复。

teu*_*and 7

我认为奥利弗的想法是正确的。

我不认为该theme_custom函数是检查条件主题图的正确位置,因为主题函数大多不知道它们添加到的精确图。

相反,我认为检查情节的合适位置是将主题添加到情节时。您可以编写如下所示的主题函数,为输出设置不同的类。

theme_custom <- function() {
  out <- theme_minimal()
  class(out) <- c("conditional_theme", class(out))
  out
}
Run Code Online (Sandbox Code Playgroud)

现在,每次将主题添加到情节时,都是通过ggplot_add.theme函数完成的,我们可以为conditional_theme类重写该函数。在我看来,检查图是否有分面的正​​确方法是检查plot$facet插槽的类FacetGridFacetWrap当添加适当的分面时可以是等FacetNull,没有设置分面时默认为。

ggplot_add.conditional_theme <- function(object, plot, object_name) {
  if (!inherits(plot$facet, "FacetNull")) {
    object <- object + theme(panel.border = element_rect(colour = "grey50", fill = NA))
  }
  plot$theme <- ggplot2:::add_theme(plot$theme, object, object_name)
  plot
}
Run Code Online (Sandbox Code Playgroud)

现在用例应该按预期工作:

ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  facet_wrap(vars(cyl)) +
  theme_custom()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  theme_custom() 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

唯一的缺点是您实际上每次都必须将主题添加到情节中,并且您不能使用 将theme_set(theme_custom())其应用于会话中的任何情节。