Search code examples
rggplot2facet

ggplot: set a time range for facets plotting based on date


I just want to look at the trend (i.e., Y) in a time series dataset from 7am to 9am everyday.

Do you know how to plot it in ggplot?

Each subfigure in the ggplot facet shows the trend Y from 7am to 9am each day (2010/1/1 to 2010/1/14).

Here is my dataset:

  DateTime <- seq(as.POSIXct("2010/1/1 00:00"), as.POSIXct("2010/1/15 00:00"), "min")
  Y <- rnorm(n=length(DateTime), mean=100, sd=1)
  df <- data.frame(DateTime, Y)

Thanks a lot!


Solution

  • require(ggplot2)
    df <- dplyr::filter(df, format(DateTime, '%H:%M:%S') < '09:00:00', format(DateTime, '%H:%M:%S') > '07:00:00')
    
    df$Day <- format(df$DateTime, '%d')
    
    plt <- ggplot(df, aes(DateTime, Y)) + geom_line() + facet_wrap(~Day, ncol = 2, scales = 'free_x') +
    theme(axis.text.x = element_text(size = rel(0.7)))
    
    print(plt)
    

    Output Image