Home > Blockchain >  Is there a way to detect if a scale_linetype_manual has been added to a ggplot?
Is there a way to detect if a scale_linetype_manual has been added to a ggplot?

Time:02-11

I need to be able to detect whether a ggplot passed into a function already has a scale_linetype_manual added to it so that I know whether to use ggnewscale and add another new_scale("linetype") to it.

CodePudding user response:

This function should do the trick:

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)
}

So, setting up an example:

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()

Of the above plots, only p2 should give us TRUE when passed to has_linetype_manual

has_linetype_manual(p1)
#> [1] FALSE
has_linetype_manual(p2)
#> [1] TRUE
has_linetype_manual(p3)
#> [1] FALSE

Created on 2022-02-10 by the reprex package (v2.0.1)

  • Related