Skip to content

Gantt charts using Mermaid

Last updated:

Gantt Chart

Introduction

Mermaid is a language for designing code-based diagrams. Github supports it so it great for adding illustrative diagrams into README.md files for version controlled documentation or into PR descriptions for describing new or modified processes.

A Gantt chart is a special kind of bar chart useful for project planning. Each task is represented as a horizontal bar aligned on a timeline on the x-axis. It helps with visualising inter-task dependencies and how these can affect a time schedule.

Each task on a Gantt chart has a start date, either an explicit date, or an implicit one that is derived from the end date of one or more other tasks (such dependencies are expressed with the after keyword in mermaid).

More details on the mermaid syntax for Gantt charts can be found in the official docs: https://mermaid.js.org/syntax/gantt.html

An example chart in mermaid

gantt
title Gantt Chart
dateformat YYY-MM-DD
section Section
task1 :active, crit, a1, 2020-03-07, 4d
task2 :crit, a2, after a1, 3d
task3 :a3, 2020-03-09, 3d
task4 :a4, after a1 a3, 2d
section Section2
task1 :a5, 2020-03-07, 1d

An interactive editor for experimenting with mermaid’s graphing abilities can be found here: https://mermaid.live/.

The editor on Github works as well, there the above definition renders like this:

Gantt Chart

JSON data representation

A JSON object for the data of this chart could look like this:

[
{
"sectionName": "Section",
"tasks": [
{
"id": "a1",
"name": "task1",
"tags": ["active", "crit"],
"startDate": "2020-03-07",
"duration": "4d"
},
{
"id": "a2",
"name": "task2",
"tags": ["crit"],
"afterTasks": ["a1"],
"duration": "3d"
},
{
"id": "a3",
"name": "task3",
"startDate": "2020-03-09",
"duration": "3d"
},
{
"id": "a4",
"name": "task4",
"afterTasks": ["a1", "a3"],
"duration": "2d"
}
]
},
{
"sectionName": "Section2",
"tasks": [
{
"name": "task5",
"id": "a5",
"startDate": "2020-03-07",
"duration": "1d"
}
]
}
]

Converting JSON data to mermaid chart

A function to convert a task object from above into a mermaid string could look something like this:

function taskToMermaidTask(task) {
const {
id,
name,
tags,
startDate,
afterTasks,
duration
} = task;
const metadata = [
tags ? tags.join(', ') : null, // tags must be the in front
id,
startDate,
afterTasks ? `after ${afterTasks.join(' ')}` : null,
duration
].filter(Boolean);
return `\t\t${name}\t:${metadata.join(', ')}`;
}