Search code examples
rhighchartsr-highcharter

How to use date range for highcharter columnrange plot?


I am trying to create a columnrange graph using Highcharter where the column represents a range of dates. While this works with integers, it does not work with dates. Other plot types seem to work fine handling dates.

Using the weather df as an example:

weather2 <- weather %>%
  filter(date <  mdy("03-31-2014"))%>% 
  mutate(low = date, high=date+30, id = row_number()) %>% 
  select(id, low, high)


hchart(weather2,
       type = "columnrange",
       hcaes(x = id, high=high, low=low)) 

The plot just renders as blank, with just x axis labels.

However, if I just convert the date to integers, it displays a range as expected.

weather3 <- weather %>%
  filter(date <  mdy("03-31-2014"))%>% 
  mutate(low = as.integer(date), high=as.integer(date+30), id = row_number()) %>% 
  select(id, low, high)

hchart(weather2,
       type = "columnrange",
       hcaes(x = id, high=high, low=low)) 

I have also tried adding %>% hc_yAxis(type = "datetime") , but that does not help either.

Thanks!


Solution

  • It seems that the columnrange plot type requires the date to be in timestamp format. They can be converted using the datetime_to_timestamp function in highcharter, and then using hc_yAxis(type = "datetime").

    weather2 <- weather %>%
      filter(date <  mdy("03-31-2014"))%>% 
      mutate(low = datetime_to_timestamp(date), 
             high = datetime_to_timestamp(date+30), 
             id = row_number()) %>% 
      select(id, low, high)
    
    
    hchart(weather2,
           type = "columnrange",
           hcaes(x = id, high=high, low=low)) %>% 
    hc_yAxis(type = "datetime")