By·

How to Use Mermaid.js in Jupyter Notebooks and Python Projects

Render Mermaid diagrams directly in Jupyter Notebooks, Python scripts, and data pipelines — with zero JavaScript. Copy-paste examples for matplotlib-style inline diagrams.

Rendered How to Use Mermaid.js in Jupyter Notebooks and Python Projects
Rendered example. Copy the first code block below to edit it.

# How to Use Mermaid.js in Jupyter Notebooks and Python Projects

You're analyzing data in a Jupyter notebook. You want to show a flowchart of your pipeline, a sequence diagram of API calls, or an ER diagram of your database schema — right next to your pandas DataFrames. But Mermaid is JavaScript. You're in Python.

Good news: there are three dead-simple ways to render Mermaid diagrams in Python environments, and they all work with zero JavaScript knowledge. You write Mermaid syntax as a Python string, and the diagram appears inline — just like \plt.show()\.

This guide covers Jupyter Notebook, Google Colab, and plain Python scripts, with copy-paste examples for each.

---

Method 1: IPython \`display\` with the Mermaid Package (Recommended)

The \mermaid\ package on PyPI is the simplest option. Install it once, then render any diagram with one function call.

Setup

\\\`bash

pip install mermaid

\\\`

Basic Example

\\\`python

import base64

from IPython.display import Image, display

import mmdf

def mermaid_to_image(code: str) -> bytes:

"""Convert Mermaid code to a PNG bytes object."""

return base64.b64decode(mmdf.mermaid_to_png(code))

# Define your diagram

diagram_code = """

graph TD

A[Raw Data] --> B[Clean & Validate]

B --> C[Feature Engineering]

C --> D[Model Training]

D --> E[Evaluation]

E --> F{Pass Threshold?}

F -->|Yes| G[Deploy Model]

F -->|No| C

"""

# Render inline

img_bytes = mermaid_to_image(diagram_code)

display(Image(img_bytes))

\\\`

!ML pipeline flowchart rendered inline in a Jupyter cell

---

Method 2: Mermaid Magic (IPython Extension)

If you want *magic command* syntax, the \jupyterlab-mermaid\ extension lets you write diagrams in a dedicated cell:

\\\`bash

pip install jupyterlab-mermaid

\\\`

Then in a notebook cell, use the \%%mermaid\ cell magic:

\\\`

%%mermaid

sequenceDiagram

actor User

participant App

participant Auth

participant DB

User->>App: POST /login {email, password}

App->>Auth: validate_credentials()

Auth->>DB: SELECT user WHERE email=?

DB-->>Auth: user_record + hash

Auth->>Auth: bcrypt.compare(password, hash)

Auth-->>App: JWT token

App-->>User: 200 OK {token, expires_in}

\\\`

This renders the sequence diagram inline without any Python boilerplate.

---

Method 3: Google Colab (No Install)

Colab doesn't support cell magic for Mermaid out of the box, but you can use the free Mermaid.ink API:

\\\`python

import requests

from IPython.display import Image, display

def mermaid_colab(code: str):

"""Render Mermaid in Google Colab via mermaid.ink."""

import base64, zlib

# Encode using Mermaid.ink's pako format

compressed = zlib.compress(code.encode('utf-8'), 9)

encoded = base64.urlsafe_b64encode(compressed).decode('ascii')

url = f"https://mermaid.ink/img/pako:{encoded}"

display(Image(url=url, width=600))

mermaid_colab("""

erDiagram

CUSTOMER ||--o{ ORDER : places

ORDER ||--|{ LINE_ITEM : contains

PRODUCT ||--o{ LINE_ITEM : "ordered in"

CUSTOMER {

int id PK

string email

string name

}

ORDER {

int id PK

date created_at

string status

}

PRODUCT {

int id PK

string name

float price

}

""")

\\\`

---

Method 4: Python Scripts (No Notebook)

For regular \.py\ files, save diagrams to files:

\\\`python

import mmdf

import base64

def save_mermaid(code: str, filename: str = "diagram.png"):

"""Save a Mermaid diagram as PNG."""

b64 = mmdf.mermaid_to_png(code)

with open(filename, "wb") as f:

f.write(base64.b64decode(b64))

print(f"Saved to {filename}")

save_mermaid("""

graph LR

subgraph ETL Pipeline

A[Extract] --> B[Transform]

B --> C[Load]

end

C --> D[(Data Warehouse)]

D --> E[BI Dashboard]

""", "etl_pipeline.png")

\\\`

Run the script: \python my_diagram.py\ — you get a \etl_pipeline.png\ file.

---

Which Method Should You Use?

ScenarioMethod
Jupyter Notebook / JupyterLabMethod 1 (\`mermaid\` package) or Method 2 (\`%%mermaid\` magic)
Google ColabMethod 3 (mermaid.ink API)
Python script / Airflow DAGMethod 4 (save to PNG)
Want it in a DataFrame notebookMethod 1 — sits right next to \`df.head()\`

---

Real-World Use Cases

Data engineering notebooks: Document your ETL pipeline flow right above the code that implements it.

ML model cards: Show the model architecture as a flowchart — stakeholders read diagrams; they don't read \model.summary()\.

Database schema docs: ER diagrams next to SQL queries so teammates understand relationships instantly.

API documentation in Colab: Tutorial notebooks that mix runnable Python with sequence diagrams showing the request flow.

CI/CD pipeline docs: A \%%mermaid\ cell at the top of a notebook explains the full pipeline before anyone runs a line of code.

---

Troubleshooting

"mmdf module not found" → \pip install mermaid\ (the PyPI package is called \mermaid\, but the import is \mmdf\).

Diagram renders blank in Colab → The mermaid.ink service is rate-limited. Add a \time.sleep(1)\ between renders if you're generating many diagrams.

PNG looks low-res → Pass \scale=2\ to mermaid.ink: \url = f"https://mermaid.ink/img/pako:{encoded}?scale=2"\

JupyterLab extension doesn't load → Restart JupyterLab after \pip install jupyterlab-mermaid\ and rebuild: \jupyter lab build\.

---

Mermaid in Python is the bridge between code-heavy notebooks and documentation that humans actually read. Add one diagram cell, and your notebook goes from "wall of code" to "executable design doc."