r-lib / gtable

The layout packages that powers ggplot2
https://gtable.r-lib.org
Other
87 stars 18 forks source link

gtable_trim() does not trim #81

Open pasipasi123 opened 5 years ago

pasipasi123 commented 5 years ago

I'm not sure if I understand gtable_trim() correctly. My interpretation is that it should remove empty rows and columns. The help file says that "This function detects rows and columns that does not contain any grobs and removes thewm from the gtable. If the rows and/or columns removed had a non-zero height/width the relative layout of the gtable may change."

Here I'm creating a plot with a title. I'll then filter out the title and use gtable_trim() to get rid of the remaining whitespace, but it does nothing. The plot is exactly the same without the trim (the whitespace is difficult to see in the image below).

In the examples in ?gtable_trim the trim doesn't seem to do anything either.

library(gtable)
library(grid)
library(tidyverse)

p1 <- ggplot(mtcars, aes(hp, mpg)) + geom_point() + labs(title = "Title")

p1g <- ggplotGrob(p1)

p1g <- p1g %>% 
  gtable_filter("title", invert = TRUE)

p1g %>% 
  gtable_trim() %>% 
  grid.draw()

grid.newpage()

p1g %>% 
  grid.draw()

image

pasipasi123 commented 5 years ago

I've been told that gtable_trim() doesn't do anything because there are still some grobs left after filtering, eg. a background grob. For the desired effect I can use the following workaround, where (in a quickly written function) I take a note of the top extend of the title row and change the row's height to zero.

library(gtable)
library(grid)
library(tidyverse)

p1 <- ggplot(mtcars, aes(hp, mpg)) + geom_point() + labs(title = "Title")

p1g <- ggplotGrob(p1)

delete_row <- function(x, pattern) {
  t <- x$layout %>% 
    filter(str_detect(name, pattern)) %>% 
    pull(t)

  x <- gtable_filter(x, pattern, invert = TRUE)

  x$heights[t] <- unit(0, "cm")

  x
}

grid.draw(p1g %>% delete_row("title"))