Skip to content

Instantly share code, notes, and snippets.

@diraneyya
Last active March 22, 2025 09:42
Show Gist options
  • Save diraneyya/1177344d2ead2185c0316f8b5f6ef67b to your computer and use it in GitHub Desktop.
Save diraneyya/1177344d2ead2185c0316f8b5f6ef67b to your computer and use it in GitHub Desktop.
Use Mermaid Diagrams in your IPython (i.e. Jupyter) Notebooks

You can do this either by using a public service like https://mermaid.ink or while hosting your own mermaid server. I find the latter option to be better in the long run, both in the individual and the collective sense. Below are recipes for both.

Using mermaid.ink

Use the following function defintion in your Jupyter notebook:

import base64
from IPython.display import display_svg
from urllib.request import Request, urlopen

def mm(graph):
    graphbytes = graph.encode()
    base64_bytes = base64.b64encode(graphbytes)
    base64_string = base64_bytes.decode()
    url="https://mermaid.ink/svg/" + base64_string
    req=Request(url, headers={'User-Agent': 'IPython/Notebook'})
    display_svg(urlopen(req).read().decode(), raw=True)

Using Own Mermaid Server

Clone and run TomWright/mermaid-server, which I have updated recently to use the latest CLI in TomWright/mermaid-server#140.

For this you would need a version of Goland that is older than or equal to 1.20 and Node 18. A possible combination is available in .tool-versions if you use asdf.

git clone [email protected]:diraneyya/mermaid-server.git
cd mermaid-server && make run

In the Jupyter notebook use the following:

from IPython.display import display_svg
from urllib.request import Request, urlopen

def mm(graph):
    graphbytes = graph.encode()
    # The local mermaid server running on port 80
    req=Request("http://localhost:80/generate", 
        headers={'Content-Type': 'text/plain'}, 
        data=graphbytes, method='POST')
    display_svg(urlopen(req).read().decode(), raw=True)

Calling the mm Function

mm("""graph TD
  A[Christmas] -->|Get money| B(Go shopping)
  B --> C{Let me think}
  C -->|One| D[Laptop]
  C -->|Two| E[iPhone]
  C -->|Three| F[fa:fa-car Car]
""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment