r - 如何从 ggplot 对象确定图例行数

标签 r ggplot2

给定一个带有图例的 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/

相关文章:

r - 如何使用 ggvis 标记绘图刻度线

删除反向重复行

r - 如何在 ggplot2 中删除点和扩展箱线图

r - 如何增加ggplot2图例中点的大小?

r - 如何使用 ggplot2 将两个 geom_tile 彼此相邻绘制,以便它们像在热图中一样对齐?

r - 在同一帧中绘制两个函数

r - 为什么 match.call 有用?

R图R水平图

Linux 使用交换而不是 RAM 进行大图像处理

r - 如何将高斯曲线添加到使用 qplot 创建的直方图?