gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:29:05 27 4
gpt4 key购买 nike

我正在研究自定义 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 Community并没有得到答复。

最佳答案

我认为奥利弗的想法是正确的。
我不认为 theme_custom function 是检查条件主题图的正确位置,因为主题函数大多不知道它们添加到的精确图。
相反,我认为检查情节的合适位置是将主题添加到情节时。您可以编写如下所示的主题函数,为输出设置不同的类。

theme_custom <- function() {
out <- theme_minimal()
class(out) <- c("conditional_theme", class(out))
out
}
现在,每次将主题添加到情节时,都是通过 ggplot_add.theme 完成的。函数,我们可以重写 conditional_theme类(class)。在我看来,检查情节是否分面的正确方法是检查 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()
enter image description here
ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
theme_custom()
enter image description here
唯一的缺点是您实际上每次都必须将主题添加到情节中,并且您不能使用 theme_set(theme_custom())将此应用于 session 中的任何情节。

关于r - 根据方面的存在有条件地修改ggplot主题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58149562/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com