Last active
July 18, 2025 17:47
-
-
Save MLKrisJohnson/2d2df47879ee6afd3be9d6788241fe99 to your computer and use it in GitHub Desktop.
Displaying Mermaid Diagrams in a Jupyter Notebook Using Python
Does display_svg(..., raw=True)
work well for you?
In Jupyter sure, but most ways I tried of embedding SVG into notebook don't render well on NBViewer/GitHub/GitLab/both. Images linking to src="https://mermaid.ink/..." is fine, it's the actually embedding the image into .ipynb that's giving me trouble. [old man yelling at cloud]
- Disabling
%%{init: { "htmlLabels": false, "flowchart": { "htmlLabels": false } } }%%
, when possible, generally makes SVG more compatible. Not enough β before / after β but hopefully more future-proof. - NBViewer issue, looks like GitHub uses βsame code? GitLab OTOH renders SVG practically fine π
- With current JupyterLab (4.4.3), I don't even need external conversion services! Turns out that emitting "text/vnd.mermaid" MIME type not only renders locally, but adds back the SVG representation to the cell, and saves that to .ipynb β¨
Combined with GitLab hosting, is closest I found to the holy grail of locally authorable & locally viewable & easy to share notebooks.
https://gitlab.com/cben/sandbox/blob/6bdb770ff0a64e5187eed927b71ef866c056e70d/jupyter_notebook/mermaid_mime_type.ipynb (usingdisplay()
for side-effect output), https://gitlab.com/cben/ipywm-notes/-/blob/8bc4e93498af3371ee04e8c899b2ae23e8296d5c/HANDOFF.ipynb (a Mermaid class with rich repr + magic). - ```mermaid fenced blocks render fine in markdown files on GitHub/GitLab β but not yet in markdown notebook cells.
For now, splitting diagrams to separate code cells is best solution I found :-/ Unfortunately, "Collapse code" to hide the diagram source in Jupyter is NOT honored by GitLab rendering. - GitLab renders SVGs with pretty low height; scrollable but it doesn't know the "true" size of the diagram, cause it sticks it in an iframe π.
Ooof, those mermaid.ink external images are maybe not so bad? π
π€ personally, I'll take the imperfect-yet-working GitLab as good enough; people who want better view can clone & open notebook locally...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have to say that this is the first time I learn that
.mmd
is rendered as a Mermaid diagram in GitHub. I know that.md
files do not support Mermaid in Gists which is why this is actually very useful. I am also pleased to see that there are two files in this Gist, which illustrates that Gists are actually just git repositories. Thank you!