graph TD A[Start] --> B[End 1] A --bad path--> C[End 2]
There are many times when I am reading about a long and convoluted process in a paper and I think “y’know, Mermaid exists”.
Mermaid.js is a diagramming engine written in JavaScript that builds diagrams from a relatively simple text format. The nice thing about mermaid is that it exists as a JavaScript plugin that can be included into your webpage.
I use the flowchart diagram the most within my Quarto documents. Here’s an example of a two-branch process.
And here’s the code I used to generate the above diagram:
```{mermaid}
graph TD1]
A[Start] --> B[End 2]
A --bad path--> C[End ```
Some notes on this code:
- We need to declare the graph type at the beginning of a diagram. For flowchart diagrams, we can use
graph TD
(top-down orientation) orgraph LR
(left-right orientation). - We give nodes names by encasing them in
[]
,()
, or a combination of the two. - We connect nodes by using
-->
, and can add labels by putting them between--
and-->
. - Once a node is defined, we refer to it by its ID (
A
, for example).
DiagrammeR
We can play with Mermaid Diagrams using the DiagrammeR
package. We can cut and paste our graph as a string to the DiagrammeR
function:
Try it Out!
Subgraphs
The key with Mermaid is that you usually don’t have control over the layout. You are specifying conditions that the layout diagram must fulfill.
You have a little more control through the use of subgraphs. You can wrap a set of nodes in subgraph <name>
, where <name>
is your name for the subgraph, and end
. Mermaid will try to group the nodes in the subgraph together.
We can try to group C
and E
into a subgraph:
Try adding in Node D
into the subgraph.
Adding Links
One of my favorite things to do is to add clickable links to nodes:
graph TD A[Start] --> B[End 1] A --> C[Click Me] A --> E[End 3] C --> D[Click Me 2] subgraph sub C E end click C https://quarto.org click D https://quarto.org/docs/authoring/diagrams.html
library(DiagrammeR)
DiagrammeR(
"graph TD
A[Start] --> B[End 1]
A --> C[Click Me]
A --> E[End 3]
C --> D[Click Me 2]
subgraph sub
C
E
end
click C https://quarto.org
click D https://quarto.org/docs/authoring/diagrams.html
" )
Resources
Citation
@online{laderas2025,
author = {Laderas, Ted},
title = {Mermaid and {DiagrammeR} - {Amazing} for {Diagrams}},
date = {2025-02-02},
langid = {en}
}