有没有办法检测scale_linetype_manual是否已添加到ggplot中?

una*_*der 1 r ggplot2 ggnewscale

我需要能够检测传递给函数的 ggplot 是否已经添加了scale_linetype_manual一个,以便我知道是否使用并向其ggnewscale添加另一个。new_scale("linetype")

All*_*ron 5

这个函数应该可以解决问题:

has_linetype_manual <- function(p) {
  x <- sapply(p$scales$scales, function(x) x$aesthetics == "linetype")
  y <- sapply(p$scales$scales, function(x) as.list(x$call)$scale_name == "manual")
  if(length(x) == 0) FALSE else any(x & y)
}
Run Code Online (Sandbox Code Playgroud)

因此,设置一个示例:

library(ggplot2)

p1 <- ggplot(iris, aes(x = Sepal.Width, linetype = Species)) + geom_density()

p2 <- p1 + scale_linetype_manual(values = c(4, 5, 6))

p3 <- p1 + scale_linetype_discrete()
Run Code Online (Sandbox Code Playgroud)

在上面的图中,只有当传递给我们时才p2应该给我们TRUEhas_linetype_manual

has_linetype_manual(p1)
#> [1] FALSE
has_linetype_manual(p2)
#> [1] TRUE
has_linetype_manual(p3)
#> [1] FALSE
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2022 年 2 月 10 日创建(v2.0.1)