Is there a way to get to know if a ggplot object is based on geom_line?
goal: I want to write a function which adds additional object to a ggplot figure if it is a line graph.
Thank you for your answer,
Marcell
Is there a way to get to know if a ggplot object is based on geom_line?
goal: I want to write a function which adds additional object to a ggplot figure if it is a line graph.
Thank you for your answer,
Marcell
This is kind of a hacky solution to check whether a ggplot
object contains a layer with the class GeomLine
. The function has_geom_line()
iterates over the layers to check class inheritance. It returns TRUE
if any layers are geom_line()
, FALSE
otherwise.
library(ggplot2)
library(magrittr)
has_geom_line <- function(plot) {
stopifnot(is.ggplot(plot))
any(purrr::map_lgl(plot$layers, ~inherits(.x$geom, "GeomLine")))
}
p <-
mtcars %>%
ggplot(aes(hp, mpg)) +
geom_line() +
geom_point()
has_geom_line(p)
#> [1] TRUE
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.