Search code examples
rggplot2grid-layout

R Data Viz - possible to create a grid of rectangles with grid, ggplot or another data viz library


enter image description here

The attached image is a screenshot that I've mocked up quickly in excel, however I am going to need a reproducible data visualization based on this layout, which is a grid of rectangles with varying widths. Assume that I have the requisite data of coordinates for all rectangles that would be required to create such a graph.

Is something like this possible to do in R, with ggplot2 or any other data viz libraries? My fallback is to create a custom solution using Javascript / D3, however our strong initial preference is to find a solution that works in R.

Edit: This link using grid and grid.rect to create rectangles on the cartesian grid. It seems like a decent baseline option, if no better alternatives are available.

Edit2: Here's a small example of some data:

> dput(zed)
structure(list(time = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
), a1 = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3), a2 = c(4, 4, 5, 
5, 5, 5, 5, 6, 6, 6, 6, 6), a3 = c(7, 7, 7, 8, 8, 8, 9, 9, 9, 
10, 10, 10), a4 = c(11, 11, 11, 11, 11, 12, 12, 12, 13, 13, 13, 
13)), class = "data.frame", row.names = c(NA, -12L))
> zed
   time a1 a2 a3 a4
1     1  1  4  7 11
2     2  1  4  7 11
3     3  1  5  7 11
4     4  1  5  8 11
5     5  2  5  8 11
6     6  2  5  8 12
7     7  2  5  9 12
8     8  2  6  9 12
9     9  3  6  9 13
10   10  3  6 10 13
11   11  3  6 10 13
12   12  3  6 10 13

a1, a2, a3, a4 represent the 4 rows, the y-values for these rows do not matter all too much. time represents the linear x-values. For each row (for a1, for example), a rect should end when the values change from one number to another. a1, the first row then, would have 3 rectangles each with width == 4. The numbers in the columns can also serve as the text displaying in the rects.

I'm actively working on a solution using ggplot2::geom_rect (thank you for right direction on this), and will post an update if I come to a solid solution.


Solution

  • Try something like this:

    library(ggplot2)
    library(dplyr)
    #Code
    zed %>% pivot_longer(-time) %>%
      ggplot(aes(x=factor(time),y=name,
                 fill=value))+
      geom_tile()+
      xlab('Time')+ylab('Var')+
      scale_fill_gradient2()
    

    Output:

    enter image description here