Search code examples
rtimeserieschart

plot bar chart for time series data based on factor value (1,0)


I have a dataframe/tibble which looks likes:

z <- tibble(Time = as.POSIXct(c(
            '2020-01-06 00:22:15',
            '2020-01-06 00:45:16',    
            '2020-01-06 00:46:37',    
            '2020-01-06 01:29:55')), 
            Value = c(0,1,0,1))

and I want to plot something like bar chart using time series and value data Please see attachment as I can't add inline images yet.


Solution

  • You can have the use of geom_rect from ggplot2. To prepared your tibble for the plotting, you can create a column used for setting the xmax that will correspond to the sequential time.

    library(dplyr)
    library(ggplot2)
    z %>% mutate(xmax = lead(Time), y = 0) %>%
      ggplot(aes(xmin = Time, xmax = xmax, ymin = y, ymax =y+1))+
      geom_rect(aes(fill = as.factor(Value)))+
      theme(axis.text.y = element_blank(),
            legend.title = element_blank())
    

    enter image description here

    Does it answer your question ?