我正在研究一个自定义的 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()
}
}
如果这是可能的,它在使用中看起来像这样:
library(ggplot2)
# plot with facets automatically adds panel borders
ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
facet_wrap(vars(cyl)) +
theme_custom()

# plot without facets no panel border
ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
theme_custom()

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

