Search code examples
rr-highcharter

Date format for tooltip and axis in Highcharter R


I have the following dataset:

library(highcharter)
datasample <- data.frame(month = c("2020-01-01","2020-02-01","2020-03-01"),
                         sales = c(10000,15000,2000),
                         margin = c(0.34,0.33,0.31))

datasample$month <- as.Date(datasample$month)

What I want is to plot the sales per month, but to add the margin in the secondary axis. So I tried this code:

highchart() %>% 
  hc_yAxis_multiples(
    list(lineWidth = 3),
    list(showLastLabel = FALSE, opposite = TRUE)
  ) %>% 
  hc_add_series(datasample, hcaes(x = month, y = sales), 
                yAxis=0, type = "area", name = "Sales") %>%
  hc_add_series(datasample, hcaes(x = month, y = margin), 
                yAxis=1, type = "line", name = "Margin") 

The problem with the plot is that the date is formatted as a long sequence of numbers (perhaps a timestamp). I tried to add this code but works only for the axis, not the tooltip:

%>%
  hc_xAxis(labels = list(format = '{value:%m %Y}'))

enter image description here

Please, could you help me with this plot? Thank you.


Solution

  • Use type = "datetime" in hc_xAxis.

    library(highcharter)
    
    highchart() %>% 
      hc_yAxis_multiples(
        list(lineWidth = 3),
        list(showLastLabel = FALSE, opposite = TRUE)
      ) %>% 
      hc_add_series(datasample, hcaes(x = month, y = sales), 
                    yAxis=0, type = "area", name = "Sales") %>%
      hc_add_series(datasample, hcaes(x = month, y = margin), 
                    yAxis=1, type = "line", name = "Margin") %>%
      hc_xAxis(dateTimeLabelFormats = list(day = '%m  %Y'), type = "datetime")
    

    enter image description here