Search code examples
rdata-visualizationggvis

R ggvis date slider by month for interactive graph


I'm attempting to make an interactive time series chart with ggvis, with a slider that will default using all data, but when sliding to right will cut the oldest data by month. Data is monthly, but I can not figure out how to make it work. Consider:

retail <- data.frame(Date = seq.Date(as.Date(parse_date_time("1/1/2007", "%m/%d/%y"))
                          , as.Date(parse_date_time("2/1/2017", "%m/%d/%y")),
                          by="month"),
                 Measure = rnorm(122))

u <- melt(retail, id="Date", measure = "Measure")

# Works for static graph
u %>%
  ggvis(~Date, ~value)

# Defaults to daily slider, no data displayed
u %>% 
  ggvis(~Date,~value) %>%
  layer_lines(input_slider(min(u$Date), max(u$Date), value=min(u$Date)))

I can not get the slider to control the Date variable, it keeps defaulting to daily. I noticed it defaults to daily in the documentation, but I can not find a workaround to force it to work with non-daily data.


Solution

  • For readability, let's create dataSlider outside:

    library(lubridate) # for ceiling_date()
    
    dateSlider <- input_slider(min=min(u$Date), max=max(u$Date), c(min(u$Date),
     max(u$Date)), map = function(x) ceiling_date(x, "month") )
    

    map will change your arbitrary selected day from the input slider to the first day of the month. This mapped x then defines plot range.

    u %>% 
     ggvis(~Date,~value) %>% 
      layer_lines() %>%
      scale_datetime("x", nice="month", domain = dateSlider, clamp = TRUE)
    

    Edit: Removing white spaces before and after:

    dateSlider2 <- input_slider(min=min(u$Date), max=max(u$Date), c(min(u$Date),
     max(u$Date)), map = function(x) floor_date(x, "month") )
    
    u %>% 
     ggvis(~Date,~value) %>% 
      layer_lines() %>%
      scale_datetime("x", nice="month", expand=0,  domain = dateSlider2, 
       clamp = TRUE, override=TRUE)