Patrick Coyle
  • Blog

Introduction to mermaid.js

news
code
analysis
Author

Patrick Coyle

Published

April 30, 2023

mermaid.js is a Javascript library that allows you to create diagrams by writing “Markdown-ish syntax.” It has native support in Quarto:

graph LR
A[Hard edge] --> B(Round edge)
B --> C{Decision}
C --> D[Result one]
C --> E[Result two]

graph LR
A[Hard edge] --> B(Round edge)
B --> C{Decision}
C --> D[Result one]
C --> E[Result two]

Here is mermaid template for the 2023 NBA Playoffs (excluding the play-in tournament)1

library(dplyr, warn.conflicts = FALSE) # to load the magrittr pipe
my_mmd <- "playoffs_template1.mmd" %>%
  readLines(warn = F) 
my_mmd %>%
  paste(collapse = "\n") %>%
  DiagrammeR::mermaid()

We can progammatically edit this template with data about the teams and games:

library(readr)
library(stringr)
seed_xwalk <- read_csv("nba_2023_seed_xwalk.csv", na = "")
helper1_20230423 <- function (mmd) {
  mmd[-1] %>%
  str_trim() %>% 
  str_split(" --> ", simplify = T) %>% 
  as_tibble() %>% 
  setNames(c("From", "To")) %>% 
  left_join(seed_xwalk, by = c("From" = "seed")) %>% 
  transmute(
    new_edges = paste0("  ", 
                       case_when(!is.na(team_stub) ~ team_stub, T ~ From), 
                       " --> ", 
                       To)
  ) %>% 
  pull(new_edges) %>% 
  c(mmd[1], .) 
}
my_mmd %>% 
  helper1_20230423() %>% 
  paste(collapse = "\n") %>%
  DiagrammeR::mermaid()

Footnotes

  1. DiagrammeR::mermaid() does not appear to support every Mermaid diagram syntax, such as flowcharts. But the flowchart syntax can be manually entered into a Quarto mermaid code chunk.↩︎