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

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

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:

  1. # For p1
  2. legend_rows_p1 <- length(unique(p1$data$class))
  3. # For p2
  4. 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?

  1. library(dplyr)
  2. library(ggplot2)
  3. p1 &lt;- mpg %&gt;%
  4. count(drv, class) %&gt;%
  5. ggplot(aes(drv, n, fill = class)) +
  6. geom_col() +
  7. scale_fill_viridis_d(NULL, option = &quot;H&quot;) +
  8. ggtitle(&quot;class&quot;) +
  9. theme_minimal() +
  10. theme(legend.position = &quot;bottom&quot;)
  11. p2 &lt;- mpg %&gt;%
  12. count(drv, manufacturer) %&gt;%
  13. ggplot(aes(drv, n, fill = manufacturer)) +
  14. geom_col() +
  15. scale_fill_viridis_d(NULL, option = &quot;H&quot;) +
  16. ggtitle(&quot;manufacturer&quot;) +
  17. theme_minimal() +
  18. 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 作为辅助工具的函数。

  1. legend_dim <- function(plot) {
  2. leg <- cowplot::get_legend(plot)
  3. labels <- gtable::gtable_filter(leg$grobs[[1]], "label")
  4. c(
  5. length(unique(labels$layout$t)),
  6. length(unique(labels$layout$l))
  7. )
  8. }
  9. legend_dim(p1)
  10. # [1] 2 4
  11. legend_dim(p2)
  12. # [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.

  1. legend_dim &lt;- function(plot) {
  2. leg &lt;- cowplot::get_legend(plot)
  3. labels &lt;- gtable::gtable_filter(leg$grobs[[1]], &quot;label&quot;)
  4. c(
  5. length(unique(labels$layout$t)),
  6. length(unique(labels$layout$l))
  7. )
  8. }
  9. legend_dim(p1)
  10. # [1] 2 4
  11. legend_dim(p2)
  12. # [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:

确定