rggplot2visualizationtimeline

Timeline visualization with ggplot2: How to make parallel events visible?


I want to draw a timeline with ggplot2. Some of the events take place at the same time and ggplot2 tends to draw them on top of each other, such that only one of them stays visible.

Here is an example table of events:

library(tidyverse)
events <- 
  tribble(
    ~group,   ~name,          ~start,       ~end,         ~color,
    "group1", "first event",  "2023-09-19", "2023-11-19", "color1",
    "group1", "in parallel",  "2023-09-19", "2023-11-19", "color2",
    "group1", "later",        "2024-09-01", "2024-09-21", "color1"
  ) |>
  mutate(start=lubridate::ymd(start),
         end=lubridate::ymd(end))

Here is the ggplot2 command so far:

ggplot(events,
       aes(xmin=start, xmax=end,
           ymin=group, ymax=group,
           col=color)) +
  scale_x_date() + 
  geom_rect(linewidth=3)

Note that the second event is drawn on top of the first, such that the user cannot see it:

plot of the timeline with first event not being visible

How can I make both events visible?

I tried all the positional adjustments that ggplot2 offered, hoping that any of them would plot the two events in parallel with displaying the correct start date and end date. position_dodge() sounded like a natural choice, however it shifts the positions of the events on the x axis such that the plot becomes incorrect.


Solution

  • One option would be to use a geom_linerange with position_dodge:

    library(ggplot2)
    
    ggplot(
      events,
      aes(
        xmin = start, xmax = end,
        y = group,
        color = color
      )
    ) +
      scale_x_date() +
      geom_linerange(
        linewidth = 3,
        position = position_dodge(width = .25)
      )