Search code examples
rechartsecharts4r

How I can customize the date format on echarts4r?


Hi and thanks for reading me I am trying to make a time series chart with Echarts4r but I would like to change the customization of the axis with the dates. My current code is as follows:

library(echarts4r)
library(lubridate)
df <- data.frame(
  date = seq.Date(from = as.Date("2019-01-01"), to = as.Date("2021-05-01"),
                  by = "month"),
  val = rnorm(29, mean = 100, sd = 50)
)
df |> 
  e_charts(date) |> 
  e_line(val)

Currently the graph looks like this:

enter image description here

But I would like it to look like this:

enter image description here

Over the years located in another row. So far I have not found a way to do it, does anyone know if it is possible somehow?

Again, thanks for the help


Solution

  • I have found a "hack" that makes it work:

    First you create a formatter in JS

    yearMonthDate <- htmlwidgets::JS('function (value) {
      var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oc", "Nov", "Dec"
      ];
      
      var d = new Date(value);
      var datestring =  monthShortNames[d.getMonth()] + "  "
      if (d.getMonth()===0) {
        var datestring =  d.getFullYear() + "  " + monthShortNames[d.getMonth()]  + "  "
        
      }
      
      
      return datestring
    }')
    

    Then you just need to incorporate like such

     data %>%
            e_charts(date) %>%
            e_bar(count) %>%
            e_x_axis(
              date, 
              axisPointer = list(show = TRUE),
              axisLabel = list(
                rotate = 45,
                formatter = yearMonthDate
              ))
    

    And you get something like that:

    enter image description here

    Of course you can change it to look more like your example and add break lines and such.