rggplot2plotheatmapfacet-grid

facet grid causing different row height in R


dt <- data.table(x = c(1, 2, 3, 4, 5),
                 y = c("a_x", "b_w", "b_x", "b_y", "b_z"),
                 gr = c("a", "b", "b", "b", "b"))
dt


ggplot(dt, aes(x = x, y = y, fill = x)) + 
  geom_tile() +
  facet_grid(rows = vars(gr),  scales = "free")

My actual code is a bit more complicated (a heatmap with each boxes filled) but the main problem I'm facing with is that(as demonstrated in this code), when different "gr" has different counts of rows, the height of each rows from different group of Y changed. How do I force them to be the same even there are different rows in each "gr", tks!


Solution

  • The issue is that each panel will have the same height and the height of the tiles will adjust to fit the full height of the panel. Hence, for groups with less rows the tiles will have a larger height. Instead you could add space="free_y" so that the height of each panel will adjust according to the number of rows and each row of tiles will have the same height:

    library(ggplot2)
    
    ggplot(dt, aes(x = x, y = y, fill = x)) +
      geom_tile() +
      facet_grid(
        rows = vars(gr),
        space = "free_y", 
        scales = "free_y"
      )