【问题标题】:Plot grobs on ggplot faceted graph在 ggplot 分面图上绘制 grobs
【发布时间】:2023-01-24 00:06:09
【问题描述】:

我有一个多面图,我想在每个面上绘制一个不同的 grob(比如一个包含汇总统计信息的表格)。我尝试使用 ggpmisc::geom_grob 将不同的 grob 放入列表中,但只有最后一个 grob 被绘制在所有方面。

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)
library(gridExtra)
#> 
#> Attaching package: 'gridExtra'
#> The following object is masked from 'package:dplyr':
#> 
#>     combine
library(ggpmisc)
#> Loading required package: ggpp
#> 
#> Attaching package: 'ggpp'
#> The following object is masked from 'package:ggplot2':
#> 
#>     annotate

p1 <- iris |> 
  ggplot(aes(x=Petal.Length)) +
  geom_density() +
  facet_wrap(vars(Species))

stats <- iris |> 
  group_by(Species) |> 
  summarise(Mean = round(mean(Petal.Length), 3),
            SD = round(sd(Petal.Length), 3))

g1 <- filter(stats, Species == "setosa") |> tableGrob(rows=NULL)
g2 <- filter(stats, Species == "versicolor") |> tableGrob(rows=NULL)
g3 <- filter(stats, Species == "virginica") |> tableGrob(rows=NULL)

grobs <- tibble(x=4, y=2, grobs = list(g1,g2,g3))

p1 +
  geom_grob(data=grobs, aes(x=x, y=y, label=grobs))

创建于 2023-01-23 reprex v2.0.2

【问题讨论】:

    标签: r ggplot2 facet grob


    【解决方案1】:

    您没有在 grobs 数据框中包含分面变量 (Species),因此 ggplot 不知道如何在分面之间分配这些 grob。

    如果您将带有适当标签的 Species 列添加到您的 grobs 数据框,那么每个表格 grob 都将绘制在其相应的面上。

    grobs <- tibble(x=4, y=2, grobs = list(g1,g2,g3), 
                    Species = c('setosa', 'versicolor', 'virginica'))
    
    p1 + geom_grob(data = grobs, aes(x = x, y = y, label = grobs))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      相关资源
      最近更新 更多