我认为奥利弗的想法是正确的。
我不认为theme_custom
function 是检查条件主题绘图的正确位置,因为主题函数大多不知道它们所添加到的精确绘图。
相反,我认为检查情节的适当位置是在将主题添加到情节中时。您可以编写如下所示的主题函数,该函数为输出设置不同的类。
theme_custom <- function() {
out <- theme_minimal()
class(out) <- c("conditional_theme", class(out))
out
}
现在,每次将主题添加到情节中时,都是通过ggplot_add.theme
函数,我们可以将其重写为conditional_theme
班级。在我看来,检查情节是否分面的正确方法是检查情节的类别plot$facet
槽,可以是FacetGrid
, FacetWrap
等当添加适当的方面并默认为FacetNull
当没有设置facet时。
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
}
现在用例应该按预期工作:
ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
facet_wrap(vars(cyl)) +
theme_custom()
ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
theme_custom()
唯一的缺点是你每次都必须将主题添加到情节中,并且不能使用theme_set(theme_custom())
将此应用于会话中的任何绘图。