问题
如何以编程方式查找给定的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