确定ggplot对象中图例行数的方法

huangapple go评论128阅读模式
英文:

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 &lt;- mpg %&gt;% 
  count(drv, class) %&gt;% 
  ggplot(aes(drv, n, fill = class)) +
  geom_col() +
  scale_fill_viridis_d(NULL, option = &quot;H&quot;) +
  ggtitle(&quot;class&quot;) +
  theme_minimal() +
  theme(legend.position = &quot;bottom&quot;)

p2 &lt;- mpg %&gt;% 
  count(drv, manufacturer) %&gt;% 
  ggplot(aes(drv, n, fill = manufacturer)) +
  geom_col() +
  scale_fill_viridis_d(NULL, option = &quot;H&quot;) +
  ggtitle(&quot;manufacturer&quot;) +
  theme_minimal() +
  theme(legend.position = &quot;bottom&quot;)

确定ggplot对象中图例行数的方法

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 &lt;- function(plot) {
  leg &lt;- cowplot::get_legend(plot)
  labels &lt;- gtable::gtable_filter(leg$grobs[[1]], &quot;label&quot;)
  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

huangapple
  • 本文由 发表于 2023年6月13日 02:38:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76459426.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定