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.
Asked
Active
Viewed 45 times
1

Bear Bile Farming is Torture
- 4,317
- 4
- 27
- 61
-
1Will it cause a problem to call `new_scale("linetype")` if you don't already have one? – Dan Adams Feb 10 '22 at 13:02
-
I have ran into an edge where it does make a difference. Either bug in my code or bug in ggnewscales if that is not intended behavior. – Bear Bile Farming is Torture Feb 10 '22 at 13:03
-
Good to know, thanks. If you have a mre and it seems like a bug in the package, might be good to post it as an issue on GitHub. – Dan Adams Feb 10 '22 at 13:17
-
ggnewscale mantainer here. If you feel you found a bug, please do open an issue with a reproducible example. :) – Elio Campitelli Mar 04 '22 at 15:49
1 Answers
5
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)

Allan Cameron
- 147,086
- 7
- 49
- 87