确定 ggplot 是否有图例。

3

问题

如何以编程方式查找给定的ggplot对象是否具有图例?我考虑先将其转换为grob,然后检查布局中是否有guide-box,但这感觉有点hackish。有没有可靠且可重复的方法来完成这项任务?

代码

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
1个回答

5
一个简单的函数(尽管我认为你的方法也很好):
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接