Reputation: 20399
Question
How would I find out programatically if any given ggplot
object has a legend? I was thinking of transforming to a grob
first and check whether there is a guide-box
in the layout, but that feels a bit hackish. Any suggestions on how to do that in a reliable & reproducible way?
Code
library(ggplot2)
library(grid)
bp <- ggplot(iris, aes(Petal.Length, Petal.Width)) + theme(legend.position = "top")
noLegend <- bp + geom_point()
withLegend <- bp + geom_point(aes(color = Species))
gNoLegend <- ggplotGrob(noLegend)
gWithLegend <- ggplotGrob(withLegend)
any(gNoLegend$layout$name == "guide-box")
# [1] FALSE
any(gWithLegend$layout$name == "guide-box")
# [1] TRUE
Upvotes: 3
Views: 171
Reputation: 35382
A simple function (although I think your method is fine too):
check_for_legend <- function(x) {
'gtable' %in% class(try(cowplot::get_legend(x), silent = TRUE))
}
check_for_legend(noLegend)
FALSE
check_for_legend(withLegend)
TRUE
Upvotes: 5