英文:
How to determine number of legend rows from ggplot object
问题
You can programmatically determine the number of rows in the legend of a ggplot object like p1
or p2
by using the following code:
# For p1
legend_rows_p1 <- length(unique(p1$data$class))
# For p2
legend_rows_p2 <- length(unique(p2$data$manufacturer))
These lines of code will count the unique values in the respective legend data, giving you the number of rows in each legend programmatically.
英文:
Given a ggplot object with a legend, how can I tell how many rows the legend has programmatically? (Rather than having to manually look at the plot.) e.g., given these two plots, how can I get p1
to tell me its legend has 2 rows and p2
3 rows?
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")
I've poked around the results of ggplot_build(p1)
, but without any luck.
答案1
得分: 4
这似乎可以获取图例 grob 并计算唯一的行/列起始位置。这是一个使用 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
这将返回行数和列数。
英文:
It seems like you can grab the legend grob and count the unique row/column starts. Here's a function that uses cowplot
as a helper.
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
This returns rows/columns
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论