Dynamic diagrams with Mermaid
Mihalis Tsoukalos explains how to use Mermaid to create beautiful technical graphs and diagrams you can reuse and update anywhere.
Mihalis Tsoukalos explains how to use
Mermaid to create beautiful technical graphs and diagrams you can reuse and update anywhere.
The subject of this tutorial is Mermaid, which is a Markdown dialect. Put simply, Mermaid code looks like Markdown code and enables you to create flows, diagrams, charts and more. It’s based on Javascript that renders the Markdown as code to generate the output, because Markdown doesn’t offer support for drawing. Mermaid is supported by many editors including Microsoft Visual Code and typora, which we’ll cover here. There are also online editors that can render Mermaid code and create the respective output.
Mermaid code is delivered in blocks. The first line of a Mermaid block specifies the type of the plot. Valid values include graph, pie, sequence diagram and flowchart. Each plot type has its own syntax, and it’s much easier to include Mermaid code in Markdown files that use the md file extension (filename.md), which is what we’ll be using for the examples of this tutorial.
A Mermaid block in a Markdown file begins with ```mermaid and ends with ``` – this is the Markdown way of telling that the embedded code has a given property, which in this case is Mermaid. However, Mermaid code can also be saved on its own in files that use the mmd file extension (filename.mmd).
Installing Mermaid… or not!
You don’t need to install Mermaid. All you need is an editor that supports Mermaid to see the output from a Mermaid block. The following is a Markdown file, saved as mermaid.md, with a block in Mermaid format:
## This is a Mermaid example
```mermaid graph TD;
A1-->A2;
A2-->A4;
A1-->A3;
A2-->A3;
A3-->A4;
```
The first line is plain Markdown and generates a title in the output. Then, we declare that we’re creating a graph that’s going to be rendered from the top to the bottom (TD: Top-down) of the page. Next, we add nodes and we connect them with other nodes. The --> notation shows that the node on the left is connected to the node on the right. The graph contains four nodes, named A1, S2, A3 and A4. If you want to include more nodes and connections between them, just declare what you want – Mermaid takes care of the output.
This example illustrates one of the simplest uses of Mermaid; it can do many more tasks. However, it also illustrates the simplicity of the Mermaid dialect.
The output of the previous code can be seen in the diagram (above) with the help of Microsoft Visual Code – more on this below.
Microsoft Visual Code
Microsoft Visual Code has a extension for rendering Mermaid files and previewing Mermaid output inside Visual Code. Go to the Extensions tab, search for the “Markdown Preview Mermaid Support” extension and install it. It would also be helpful to install the “Mermaid Markdown Syntax Highlighting” extension so that you can see your Mermaid code beautifully coloured. Next, we render the Markdown file vscode.md inside Microsoft Visual Code:
## A Markdown file with Mermaid!
```mermaid graph LR;
Root--> A & B & C A-->A1-->A2--->A3
B-->B1-->B2-->B3
C--->C1-->C2-->C3
```
This code presents an alternative way of creating graphs. Instead of writing multiple A-->
A-->
The screeshot (opposite) shows the preview of vscode.md using the Mermaid extension for Visual Code.
Creating a pie chart
Mermaid can easily plot pie charts and can even do the calculations for you so that the percentages of the pie chart are correct. To create a pie chart you need to begin the Mermaid block with pie . The next line should begin with title followed by the title text. After that, you need to write the dataset that’s used for generating the pie chart. Each line of the dataset is a different entry and contains a label, followed by a colon, which is followed by a positive numeric value. Note that the label text should be included in double quotes, which isn’t the case with the pie chart title text.
The following block shows the definition of a pie chart in the Mermaid dialect:
## This is a Pie Chart in Mermaid
```mermaid pie title Linux Distributions
“Debian” : 42.96
“Ubuntu” : 50.05
“Arch” : 10.01
“Centos” : 5
```
The previous code is saved in the pie_chart.md file – render it on your own to see its output.
Creating a flowchart
Flowcharts in Mermaid start with the flowchart keyword, followed by their orientation (LR or TD). Then you add the nodes of the flowchart as you would with graphs. If you want to add text in an edge you should use the
The following Mermaid code, which can be found as flow_chart.md, describes a flowchart:
## Flow chart
```mermaid flowchart TD
A[choose OS] --> B{DO you want?}; B -- Yes --> C[UNIX or Windows]; C -- Windows --> D[good Luck!]; C -- UNIX --> E{linux or macos?} E -- Linux --> G{good Choice!}
E -- macos --> H{apple.com!}
B -- No ---> F[end];
```
When rendered, the code generates a flow chart that can help you choose an Operating System. The diagram (overleaf) shows the flowchart generated by this code with the help of Microsoft Visual Code.
Sequence diagrams
A sequence diagram describes interactions and how things are carried out. They’re helpful when you want to describe situations that depend on many factors.
A sequence diagram begins with the
sequencediagram keyword followed by the list of participants, which are defined using the participant keyword (each participant is defined in a separate line). After that you need to define the connections and interactions between participants, which in Mermaid terminology are called Messages.
This Mermaid code produces a sequence diagram – it’s part of the seq_diagram.md Markdown file:
sequencediagram participant User participant CTC participant CSV participant Auth as Authorization loop Every minute
CTC-->CSV: Keep updating! end
User-->>auth: Send Authorization details Auth-->>user: Get back authorization token
There are four participants: User, CTC, CSV and Authorization. The Authorization participant is accessed
as Auth inside the Mermaid code but is displayed as Authorization for clarity – this is implemented with the Auth as Authorization statement. The loop block represents actions that happen continuously.
You should be able to see the output of seq_diagram. md either in Microsoft Visual Code, typora or any other online Mermaid editor such as https://mermaid-js.github.io/mermaid-live-editor.
Use Cases in Mermaid
Let’s see how Mermaid can describe the use cases of a project. Use cases are implemented using sequence diagrams, which means they’re defined using the sequencediagram keyword. We want to use the Mermaid code to describe how a user interacts with a program and the components involved in the process. This is shown in the following Mermaid code: sequencediagram participant U as User participant CTC participant CSV participant CTC_AUTH as CTC/AUTH autonumber rect rgb(0, 100, 0) par Get Data CSV->>CTC_AUTH: A Database that keeps Usage data
Note right of CSV: REST API CTC_AUTH-->>CSV: Return Usage data end end
U->>CTC: Logs in CTC-->>U: Returns Security Token
CTC->>CSV: Opens CSV Window
U->>CSV: Asks for system visualisations
CSV-->>CSV: Query Internal Database
CSV-->>U: Displays Visualisations
The autonumber keyword that’s shown here attaches a sequence number to each arrow in the sequence diagram. The rect rgb(0, 100, 0) command puts colour in the output using RGB values, and colours a rectangle. Inside that rectangle you can write the Mermaid commands you want. The par block shows actions that happen in parallel. Both rect and par blocks end with the
end keyword.
The diagram (above) displays the output of the previous Mermaid code – the Markdown source file with the Mermaid code is called use_cases.md. The use of
autonumber enables you to specify the part of the sequence diagram you want by using a number.
Mermaid and Hugo
The Hugo (https://gohugo.io) framework offers support for Mermaid code. This section presents such as example where we embed Mermaid code into a Hugo blog post that we publish. In order to support Mermaid rendering in Hugo, you need to add a small shortcode inside the layouts/shortcodes directory – Hugo uses shortcodes to add extra functionality that can’t be implemented in Markdown. The name of the shortcode file should be mermaid.html and must have the following content:
$ cat layouts/shortcodes/mermaid.html
{{ .Inner }}
The previous file defines a shortcode named
mermaid – in order to use that shortcode you should embed Mermaid commands in {{
Using [Mermaid](https://mermaid-js.github.io/ mermaid/) in Hugo.
{{
A-->B;
A-->C;
B-->D;
C-->D;
{{}}
The first line is regular Markdown code. After that you need to put all Mermaid related code in a block that begins with {{
The diagram (facing page) shows the code inside the Hugo blog post – the entire Markdown file for that blog post is called usemermaid.md. You can see the blog post live at www.mtsoukalos.eu/2021/01/usingmermaid/. Bear in mind that the Mermaid code is rendered with the help of the Javascript library used in the shortcode file (https://unpkg.com/mermaid@8.2.3/dist/mermaid.min.js) and not by Hugo itself.
Go scripts
This section presents a Go utility that generates Mermaid code, but you can use any programming language you want to produce Mermaid code. The utility reads a CSV file with two columns and creates a Markdown file with a title and a pie chart in Mermaid format. The first column in the CSV file is the label and the second column is the value, which should be an
integer. The filename of the input file becomes the title of the Markdown document as well as the title of the pie chart and the contents of the file generate the elements of the pie chart.
The most interesting code of piechart.go is for _, line := range lines {
_, err := strconv.atoi(line[1]) if err != nil { continue
} fmt.printf("\t\"%s\” : %s\n”, line[0], line[1])
}
The input file is read all at once and kept in the lines slice. The previous code processes the elements of the lines slice one by one to obtain the data and print it on the screen. The presented code ignores all rows that don’t contain a valid integer with the help of the strconv. Atoi() Go function.
The input file that’s processed by piechart.go has the following format:
Linux,75
Windows,10
...
Running piechart.go with the aforementioned input file produces the following output:
## data.csv
```mermaid pie title data.csv “Linux” : 75 “Windows” : 10 ... ```
The easiest way to collect the output is to redirect it into a file: run piechart.go data.csv and then filename. md. After saving the output you can process it in
Microsoft Visual Code or typora and obtain the type of output you’re looking for.
The key takeaway here is that once you understand the format of the Mermaid file you want to create, you can generate Mermaid files dynamically using input from multiple data sources, including plain text files, database servers and web services.
Python 3 scripting
Finally let’s look at how Python 3 utility that generates Mermaid output on the fly using an external service. For the purposes of this tutorial, the Mermaid code is hardcoded and kept in a Python variable. If you have experience in the Python programming language, you can add some versatility to the presented utility and write code that reads the Mermaid code from a plain text file or a database server instead. Note that you might need to install some Python 3 modules for the script to work. The presented Python 3 script saves the output into a file that’s named nodes.png – the name of the output file is hardcoded.
The core functionality of the script.py Python 3 file can be found in this code: img = Image.open(io.bytesio(requests.get ('https://mermaid.ink/img/’+base64_string).content)) plt.imshow(img) plt.savefig('nodes.png’, dpi = 300)
The first line uses an external web site (https://mermaid.ink/img) to render the Mermaid input. The second statement displays the image output – if you’re running the Python 3 script from the command line, then this statement might not generate any output on screen – and the final statement saves the generated image into a PNG file. The biggest difference between the Go script and the Python 3 one is that the Python 3 script generates the output image by itself whereas the Go script generates Mermaid code that needs to be rendered first.
Don’t get fooled by the use of Markdown and plain text files and think that Mermaid is limited in function. It’s a professional tool that can help you create beautiful technical diagrams and plots, and include them in your blog posts, documents or reports. Experimenting with Mermaid is going to make you more productive – play with it a little before using it in real projects.