Sub topic 9
Draw the chart in Mermaid and Python
This chapter turns the schedule you calculated earlier into a picture. You will draw it twice. First you will write it as text that Mermaid renders. Then you will compute it and plot it with Python and matplotlib. It assumes you can read a task list with durations and predecessors, and that you have run a short Python script. For the Python part, you need Python 3.8 or later and pip install matplotlib.
The two approaches suit different jobs:
| Approach | Strength | Weakness |
|---|---|---|
| Mermaid | Lives in Markdown, diffs cleanly in version control, and renders in many wikis and documentation tools | You enter dates by hand, and it does not calculate a critical path |
| Python | Computes dates and slack from the dependency data, so the chart cannot disagree with the numbers | Needs more code, and the output is an image |
The Mermaid task line
A Mermaid Gantt chart is a header followed by task lines. Every task line has the same shape:
Task name :tag, id, start, durationThe part before the colon is the label shown on the chart. The part after the colon is a comma-separated list of metadata. The list is read left to right, and most items are optional.
| Metadata item | Example | Meaning |
|---|---|---|
| Tag | `done`, `active`, `crit`, `milestone` | Changes the bar style or state. Tags come first, and you can combine them, as in `crit, active`. |
| ID | `des1` | A name other tasks can refer to. It must not contain spaces. |
| Start | `2026-01-05` or `after des1` | A fixed date, or the end of an earlier task. |
| Duration | `5d`, `2w`, `0d` | Length in days (`d`), weeks (`w`), hours (`h`) and so on. |
Omit the start and the task begins when the previous task in the file ends. That is convenient for a single chain of work, but it hides the logic. Prefer an explicit after for any task that has a real predecessor.
Build the chart step by step
The five-task project from the forward-pass chapter has these durations and links:
- Wireframes take 5 days.
- Mockups take 7 days and follow Wireframes.
- Backend takes 12 days and follows Wireframes.
- Frontend takes 10 days and follows Mockups.
- Integration takes 4 days and follows both Frontend and Backend.
Write it as sections that match the work breakdown structure. A launch milestone closes the chart.
Several details in this source matter.
dateFormattells Mermaid how to parse the dates you type.axisFormatcontrols how dates are printed on the axis. They are separate settings, and mixing them up is a common source of garbled axes.after dev1 back1lists two IDs separated by a space. The task then starts after the later of the two, which is the same rule asmax(finish[p] for p in preds)in the forward pass. Multiple IDs inafterneed a reasonably recent Mermaid version (10 or later). Older renderers accept only one ID.- The milestone has duration
0dand is drawn as a diamond. It marks a moment, not work. critonly changes how a bar looks. Mermaid does not check that the task is actually critical. You must mark the tasks you found with your own calculation.
Working days and sections
By default, a Mermaid duration counts calendar days. A 5d task that starts on a Friday ends on Tuesday. Add excludes weekends below dateFormat and Mermaid skips Saturdays and Sundays, so 5d means five working days. You can also list specific dates, as in excludes 2026-01-19, 2026-02-16, to take out public holidays. This matches the working-calendar idea from earlier. The task keeps its working-day length, but its bar stretches over the gap.
Sections are only visual groups. They do not create dependencies. A task in the Build section can depend on a task in Design, and it usually does.
Showing progress
The done, active and crit tags are the only built-in way to show state. Combine them as crit, done for a finished critical task. Mermaid has no percent-complete shading, so for fine-grained progress you need a different tool, or the Python approach below.
Common Mermaid errors
| Symptom | Likely cause |
|---|---|
| Chart does not render at all | A colon in a task name, or a missing `dateFormat` line |
| A task sits at today's date or the first date | Its `after` ID is misspelled or defined later in the file |
| Bars start on the wrong day | The date does not match `dateFormat`, for example `05/01/2026` against `YYYY-MM-DD` |
| Milestone looks like a thin line | The duration is not `0d`, or the `milestone` tag is missing |
| Axis shows crowded labels | `axisFormat` prints too much. Use `%d %b` or add `tickInterval 1week`. |
Define a task's ID on a line above any line that uses it in after. This keeps the file readable and avoids the missing-ID case in the table.
Compute first, then draw in Python
Mermaid draws what you tell it. If you change a duration, you must work out the knock-on effects yourself. In Python you can keep the dependency data in one place, calculate the dates, and draw from the results. The chart then cannot drift away from the numbers.
The script below does four things in one file:
- It runs the forward pass to get earliest start and finish for each task.
- It runs a backward pass to get the latest finish, then calculates slack.
- It draws one bar per task, with critical tasks in red.
- It adds a hatched box for slack, arrows for dependencies, and a diamond for the launch milestone.
import matplotlib.pyplot as plt
# name: (duration in days, [predecessors]); predecessors must appear first
tasks = {
"Wireframes": (5, []),
"Mockups": (7, ["Wireframes"]),
"Backend": (12, ["Wireframes"]),
"Frontend": (10, ["Mockups"]),
"Integration": (4, ["Frontend", "Backend"]),
}
# Forward pass: earliest start and finish
start, finish = {}, {}
for name, (duration, preds) in tasks.items():
start[name] = max((finish[p] for p in preds), default=0)
finish[name] = start[name] + duration
project_end = max(finish.values())
# Backward pass: latest finish, then slack
late_finish = {}
for name in reversed(list(tasks)):
successors = [s for s, (_, preds) in tasks.items() if name in preds]
late_finish[name] = min(
(late_finish[s] - tasks[s][0] for s in successors),
default=project_end,
)
slack = {name: late_finish[name] - finish[name] for name in tasks}
# Drawing
names = list(tasks)
row = {name: i for i, name in enumerate(names)}
fig, ax = plt.subplots(figsize=(9, 3.5))
for name in names:
critical = slack[name] == 0
ax.barh(row[name], finish[name] - start[name], left=start[name],
height=0.5, color="tab:red" if critical else "tab:blue")
if slack[name] > 0:
ax.barh(row[name], slack[name], left=finish[name], height=0.5,
fill=False, edgecolor="gray", hatch="//")
for name, (_, preds) in tasks.items():
for p in preds:
ax.annotate("", xy=(start[name], row[name]),
xytext=(finish[p], row[p]),
arrowprops=dict(arrowstyle="->", color="gray"))
ax.scatter(project_end, len(names), marker="D", color="black", zorder=3)
ax.set_yticks(range(len(names) + 1))
ax.set_yticklabels(names + ["Launch"])
ax.invert_yaxis()
ax.set_xlabel("Day")
ax.set_xlim(0, project_end + 2)
plt.tight_layout()
plt.savefig("gantt.png", dpi=150)
plt.show()
print("Project length:", project_end)
print("Slack:", slack)The script prints a project length of 26 and a slack of 5 days for Backend. Every other task has zero slack. Those are the same results you found by hand: the critical path runs through Wireframes, Mockups, Frontend and Integration.
How the drawing works
ax.barh(y, width, left=...)draws a horizontal bar. Theleftvalue is the start day and the width is the duration, so the bar spans exactly from start to finish.ax.invert_yaxis()puts the first task at the top. Without it matplotlib puts row 0 at the bottom, and the chart reads upside down.- The hatched box after Backend shows the slack. It tells the reader how far that bar can slide right before it delays the launch.
- Arrows run from the end of a predecessor to the start of its successor. They are finish-to-start links only. Other link types would need different anchor points.
- The
savefigcall comes beforeshowso the file is written even on a machine with no display, whereshowmay do nothing.
Using real dates in Python
The script uses day numbers, which keeps the arithmetic clear. To print calendar dates, add the day number to a project start date with datetime.timedelta(days=...). For working-day calendars, use numpy.busday_offset (or pandas.bdate_range) to convert a working-day offset into a date. Do not add raw days to a start date and expect weekends to be skipped. Doing so reproduces the calendar mistake that the previous chapters warned about.
Choosing between the two
Use Mermaid when the chart is documentation: a plan in a README, a design doc, or a wiki page that people will edit as text. Use Python when the schedule is data: many tasks, frequent changes, or a need to report slack and critical tasks along with the picture. A practical combination is to compute the schedule in Python and print Mermaid source from the results. You then get the calculation of the first approach and the portability of the second.
Exercise
In the Python script, Backend's duration is changed from 12 days to 20 days. What is the new project length, which tasks are now critical, and what is the slack on Frontend?
Show answer
Backend now finishes on day 25 (5 + 20). Frontend finishes on day 22, so Integration starts on day 25 (the later of the two) and finishes on day 29. The project length is 29 days. The critical path is Wireframes, Backend, Integration. Frontend's late finish is 25 (Integration's late start), so its slack is 25 - 22 = 3 days, and Mockups also has 3 days of slack.
Exercise
A Mermaid chart has the line Review :rev1, after build1, 3d, but the bar for Review appears at the very start of the chart. The task Build is defined later in the file as Build :build, 2026-02-02, 10d. Give two reasons the bar is misplaced and the fix for each.
Show answer
First, the ID in the after clause is build1, but the task's ID is build, so Mermaid cannot find it. Fix this by using the same ID in both places. Second, Build is defined after Review, and Mermaid resolves after against tasks it has already read, so the order matters. Fix this by moving the Build line above the Review line.