[英]Plot grobs on ggplot faceted graph
我有一個面 plot,我想在每個面 plot 上有一個不同的 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
您沒有在grobs
數據框中包含 faceting 變量 ( Species
),因此 ggplot 不知道如何在 facets 之間分配這些 grobs。 所有三個表都繪制在所有三個方面,您只能看到第三個,因為它是在前兩個方面繪制的。
如果您將帶有適當標簽的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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.