Search code examples
rggplot2unix-timestamp

Plot simple time axis for events


I'm looking for a solution to plot a time axis where events are marked as red vertical lines. I didn't find anything like that:

enter image description here (the height of the red lines should be equal)

The data is just a list of unix timestamps which should be plotted as red strings between a timespan.

How to plot using ggplot?


Solution

  • First, here are some sample dates:

    sampleDates <-
      sample(seq(as.Date("2016-01-01")
                 , as.Date("2016-12-31")
                 , 1)
             , 60)
    

    Then, here is an extension of the starting point from @zx8754's comment (note: mtcars is a builtin data set). Here, I add an arrow (instead of just a line), then use geom_linerange because you can get a vertical line in the legend, e.g., if you are coloring lines by event type. Everything from theme_minimal down is just shifting display options to make it prettier.

    ggplot() +
      geom_segment(
        aes(x = min(sampleDates) - 10
            , xend = max(sampleDates) + 20
            , y = 0
            , yend = 0)
        , arrow = arrow()
      ) +
      geom_linerange(
        aes(x = sampleDates
            , ymin = -1
            , ymax = 1)
        , col = "red") +
      xlab("Sample Date") +
      theme_minimal() +
      theme(axis.text.y = element_blank()
            , axis.title.y = element_blank()
            , panel.grid.major.y = element_blank()
            , panel.grid.minor.y = element_blank()
            ) +
      scale_x_date(date_breaks = "1 month"
                   , date_labels = "%Y\n%b-%d")
    

    enter image description here