tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.5k stars 2.02k forks source link

names of facet_grid() panels in gtable (panel-x-y) are inconsistent #3978

Closed fabern closed 4 years ago

fabern commented 4 years ago

The names of the grobs in the gtable representing the panels created with facet_grid() are inconsistent. I would expect them to follow the pattern panel-[row.nr]-[col.nr], but they don't.

library(ggplot2)
library(grid)
library(gtable)
dat <- data.frame(x = c(1, 1, 1, 1, 1, 1), 
                  y = c(1, 1, 1, 1, 1, 1), 
                  a = c("a1", "a1", "a1", "a2", "a2", "a2"), 
                  b = c("b1", "b2", "b3", "b1", "b2", "b3"))
p <- ggplot(dat, aes(x=x,y=y)) + 
  geom_point() + 
  facet_grid(vars(a),vars(b))

# Annotate facets with grob name:
g <- ggplotGrob(p)
gtable_panel_positions <-  g$layout[grepl("panel-", g$layout$name),]
for (it in seq_len(nrow(gtable_panel_positions))) {
  g <- gtable_add_grob(g,
                       grobs = textGrob(label=gtable_panel_positions[it,"name"]),
                       t = gtable_panel_positions[[it,"t"]],
                       l = gtable_panel_positions[it,"l"])
}
grid.newpage()
grid.draw(g)

Created on 2020-05-01 by the reprex package (v0.3.0)

fabern commented 4 years ago

Below example illustrates the issue in an alternative way by using gtable_filter():

library(ggplot2)
library(grid)
library(gtable)
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
dat <- data.frame(x = c(1, 1, 1, 1, 1, 1), 
                  y = c(1, 1, 1, 1, 1, 1), 
                  a = c("a1", "a1", "a1", "a2", "a2", "a2"), 
                  b = c("b1", "b2", "b3", "b1", "b2", "b3"))
p <- ggplot(dat, aes(x=x,y=y)) + 
  geom_point() + 
  facet_grid(vars(a),vars(b))

# Example B (requires dplyr)
p %>%
  ggplotGrob() %>%
  gtable_filter("^panel-1-1$", invert = TRUE) %>%
  gtable_filter("^panel-1-2$", invert = TRUE) %>%
  {grid.newpage(); grid.draw(.)}

Created on 2020-05-01 by the reprex package (v0.3.0)