给定一个带有图例的 ggplot 对象,我如何以编程方式知道图例有多少行? (而不必手动查看绘图。)例如,给定这两个绘图,如何让 p1
告诉我它的图例有 2 行和 p2
3 行?
library(dplyr)
library(ggplot2)
p1 <- mpg %>%
count(drv, class) %>%
ggplot(aes(drv, n, fill = class)) +
geom_col() +
scale_fill_viridis_d(NULL, option = "H") +
ggtitle("class") +
theme_minimal() +
theme(legend.position = "bottom")
p2 <- mpg %>%
count(drv, manufacturer) %>%
ggplot(aes(drv, n, fill = manufacturer)) +
geom_col() +
scale_fill_viridis_d(NULL, option = "H") +
ggtitle("manufacturer") +
theme_minimal() +
theme(legend.position = "bottom")
我已经研究了 ggplot_build(p1)
的结果,但没有任何运气。
最佳答案
似乎您可以抓取图例并计算唯一的行/列开头。这是一个使用cowplot
作为助手的函数。
legend_dim <- function(plot) {
leg <- cowplot::get_legend(plot)
labels <- gtable::gtable_filter(leg$grobs[[1]], "label")
c(
length(unique(labels$layout$t)),
length(unique(labels$layout$l))
)
}
legend_dim(p1)
# [1] 2 4
legend_dim(p2)
# [1] 3 5
这将返回行/列
关于r - 如何从 ggplot 对象确定图例行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76459426/