题
如果任何给定的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
Run Code Online (Sandbox Code Playgroud)
一个简单的功能(虽然我认为你的方法也很好):
check_for_legend <- function(x) {
'gtable' %in% class(try(cowplot::get_legend(x), silent = TRUE))
}
check_for_legend(noLegend)
Run Code Online (Sandbox Code Playgroud)
FALSE
check_for_legend(withLegend)
Run Code Online (Sandbox Code Playgroud)
TRUE