Rendering networkx graphs or graphml files via Mermaid

Using python and networkx, you may create some beautiful graphs and store them as graphml file:

This will give us the following graphml:

Unfortunately, rendering them the standard way by using draw and Graphviz is producing a bitmap file that I do not want to include in my documentation.

For example:

Will look like:

Instead of a PNG file, I would rather have the graph as mermaid to include it into my markdown based documentation.

A quick conversion may be done in a bash script via:

The resulting graph and the representation rendered by mermaid will look like:

To improve the script further, we will now add a view functionality by calling the mermaid-live-editor to present the diagram:

This will add the live-editor header and footer and encode it with base64 before calling the web browser. The translate replacing the plus to minus characters is necessary because + has a special meaning within a URL.

The resulting URL will look like:

Which you can try here.

You can find the full example scripts with my GitHub repository.

Limitations:

Graphml usually contains a lot more elements like shapes and labels. This example completely ignores them and uses only the edge information displaying the node-id as the label.

This is fine for a quick result, but usually, the id is not meant to label something, only to identify the node. Most professional graphml tools will likely change your ids at some point within the workflow, so be warned.

Further reading:

Graphml Primer

The following two tabs change content below.

Mike Bergmann

Technical software developer loving low level, bit peeking, embedded development as well as GUI, OO, and X-platform development.

Have your say