Search code examples
rgantt-chartmermaiddiagrammer

Changing the start date of a gantt chart in DiagrammeR


TL:DR - How do I adjust the x-axis of mermaid in DiagrammeR to have an arbitrary starting date show as T+000?

I'm working with mermaid in DiagrammeR. After reading this post, I learned how to start modifying the x-axis to show dates. A modified version of the example from that post is repeated here:

library(DiagrammeR)
library(htmltools)

m1 <- mermaid('
  gantt
    title Gantt With Custom Config
    section To fix
      check with Rich         :a1, 2025-02-20, 2d
      add custom config param :a2, after a1, 20d
      get bresler feedback    :a3, after a2,  2d
',height = 200)

# make a copy so we can compare in a tag list later
m2 <- m1

m2$x$config = list(ganttConfig = list(
  # a little tricky setup in what is already a hack
  #  treat this like a filter function with filter as second component in array
  #  and the time formatter in the first
  #  more than likely you will want to know your scale
  axisFormatter = list(list(
    "T+%j" # date format to return; see d3 time formatting
    ,htmlwidgets::JS(
      'function(d){ return d.getDay() == 1 }' # filter for Mondays or day of week = 1
    )
  ))
))


html_print(tagList(
  tags$h1("Modified X-Axis")
  ,m2
))

This allows me to display the x-axis as T+ddd. However, it always starts at the start of the year, not the start of my data. For example, if my data set runs from days 2025-02-10 - 2025-03-15, I want the chart to show T+0 - T+33, not T+41 - T+74.

I could spoof this by adjusting my input data to be 2025-01-01 + N (i.e. change 2025-03-15 to 2025-02-01), but that would probably lead to mistakes in later data entry.


Solution

  • I found a slightly different result, but it's close enough to work. With the base install of DiagrammeR, you cannot use axisFormat. However, after reading some online forums I found that the problem is that diagrammer uses an outdated version of mermaid. Take the following steps to update your mermaid package to something that is currently good enough:

    dist_loc <- list.files(
      find.package("DiagrammeR"),
      recursive = TRUE,
      pattern = "mermaid.*js",
      full.names = TRUE
    )
    js_cdn_url <- "https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.0.1/mermaid.min.js"
    download.file(js_cdn_url, dist_loc)
    

    While this now allows me to do

    dateFormat X
    axisFormat %s
    

    and have my entries start and end at specific times. However, I think I do lose the ability to have "T+" as part of the label. This is an acceptable tradeoff.