Search code examples
rr-highcharter

R highcharter x-axis date issue


I have a data frame contains month-end data. I'm using the stacked column chart but have an issue with the x-axis date labels. For example, it shows April under the March column.

library(highcharter)
df = data.frame(Date = as.Date(c('2020-03-31','2020-03-31','2020-04-30','2020-05-31','2020-05-31','2020-06-30')), Value = c(1,2,3,4,5,6), Country = c('US','Mexico','US','Canada','US','Canada'))
hchart(df, "column", hcaes(Date, Value, group = Country)) %>%
   hc_plotOptions(column = list(stacking = "normal"))

I tried to specify the type and labels by adding hc_xAxis(type = 'datetime', labels = list(format = '{value:%m-%Y}')), but it doesn't help. The tooltip shows the correct dates.

enter image description here


Solution

  • A simple and valuable solution is to transform dates into characters.

    library(highcharter)
     
    df = data.frame(Date = as.Date(c('2020-03-31','2020-03-31','2020-04-30',
                                     '2020-05-31','2020-05-31','2020-06-30')), 
                    Value = c(1,2,3,4,5,6), 
                    Country = c('US','Mexico','US','Canada','US','Canada'))
     
    df$Date <- as.character(df$Date)
     
    hchart(df, "column", hcaes(Date, Value, group = Country)) %>%
       hc_plotOptions(column = list(stacking = "normal")) %>%
       hc_xAxis(type="category", categories=unique(df$Date))
    

    enter image description here