Skip to main content

Create a Mermaid graph from a NetworkX graph

Project description

networkx-mermaid

Create a Mermaid graph from a NetworkX graph

PyPI - Version PyPI - Status PyPI - Python Version PyPI - Downloads Libraries.io SourceRank

Test Test  Beta Publish

Quality Gate Status Bugs Code Smells Duplicated Lines (%)

codecov Codacy Badge Codacy Badge CodeFactor DeepSource DeepSource

Snyk

PyCharm uv ruff Hatch project

Example

import threading
import webbrowser
from tempfile import TemporaryDirectory

import networkx as nx
import networkx_mermaid as nxm


# An example of a graph with multiple components
def create_graph():
    pastel_colors = ["#FFCCCC", "#CCFFCC", "#CCCCFF", "#FFFFCC", "#CCFFFF", "#FFCCFF"]
    graphs: list[nx.Graph] = [nx.tetrahedral_graph(), nx.dodecahedral_graph()]

    for i, g in enumerate(graphs):
        nx.set_node_attributes(g, {n: {"color": pastel_colors[i]} for n in g.nodes})

    graph: nx.Graph = nx.disjoint_union_all(graphs)

    graph.name = " + ".join(g.name for g in graphs)

    return graph


def create_builder():
    # Create a Mermaid Diagram Builder with custom settings

    builder = nxm.builders.DiagramBuilder(
        orientation=nxm.DiagramOrientation.LEFT_RIGHT,
        node_shape=nxm.DiagramNodeShape.ROUND_RECTANGLE,
    )
    return builder


def create_server(port: int, root_directory: str, open_browser: bool = True) -> threading.Thread:
    import http.server
    import socketserver

    url = f"http://localhost:{port}"

    class Handler(http.server.SimpleHTTPRequestHandler):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, directory=root_directory, **kwargs)

    def serve():
        with socketserver.TCPServer(('', port), Handler) as httpd:
            print("Serving at:", url)
            httpd.serve_forever()

    server_thread = threading.Thread(target=serve)
    server_thread.daemon = True
    server_thread.start()

    if open_browser:
        webbrowser.open(url)


def main():
    graph = create_graph()
    builder = create_builder()

    # Build the Mermaid Diagram
    mermaid_diagram: nxm.typing.MermaidDiagram = builder.build(graph)

    # Format the Mermaid Diagram for Markdown embedding
    markdown_diagram: str = nxm.formatters.markdown(mermaid_diagram)

    # or as single page HTML
    html_diagram: str = nxm.formatters.html(mermaid_diagram, title=graph.name)

    print('Mermaid Diagram:')
    print(mermaid_diagram)
    print(markdown_diagram)
    print(html_diagram)

    ## Save the HTML diagram to a file and serve it
    with TemporaryDirectory() as temp_dir:
        with open(f"{temp_dir}/index.html", 'w') as f:
            f.write(html_diagram)

        # Serve the HTML diagram
        create_server(port=8073, root_directory=temp_dir, open_browser=True)

        # Keep the main thread alive to allow the server to run
        try:
            while True:
                pass
        except KeyboardInterrupt:
            print("Server stopped")


if __name__ == "__main__":
    main()

Example Output Diagram

---
title: Platonic Tetrahedral Graph + Dodecahedral Graph
config:
  layout: dagre
  look: neo
  theme: neutral
---
graph LR
    AAA([0])
    style AAA fill: #FFCCCC, color: #000000
    AAE([1])
    style AAE fill: #FFCCCC, color: #000000
    AAI([2])
    style AAI fill: #FFCCCC, color: #000000
    AAM([3])
    style AAM fill: #FFCCCC, color: #000000
    AAQ([4])
    style AAQ fill: #CCFFCC, color: #000000
    AAU([5])
    style AAU fill: #CCFFCC, color: #000000
    AAY([6])
    style AAY fill: #CCFFCC, color: #000000
    AAc([7])
    style AAc fill: #CCFFCC, color: #000000
    AAg([8])
    style AAg fill: #CCFFCC, color: #000000
    AAk([9])
    style AAk fill: #CCFFCC, color: #000000
    AAo([10])
    style AAo fill: #CCFFCC, color: #000000
    AAs([11])
    style AAs fill: #CCFFCC, color: #000000
    AAw([12])
    style AAw fill: #CCFFCC, color: #000000
    AA0([13])
    style AA0 fill: #CCFFCC, color: #000000
    AA4([14])
    style AA4 fill: #CCFFCC, color: #000000
    AA8([15])
    style AA8 fill: #CCFFCC, color: #000000
    ABA([16])
    style ABA fill: #CCFFCC, color: #000000
    ABE([17])
    style ABE fill: #CCFFCC, color: #000000
    ABI([18])
    style ABI fill: #CCFFCC, color: #000000
    ABM([19])
    style ABM fill: #CCFFCC, color: #000000
    ABQ([20])
    style ABQ fill: #CCFFCC, color: #000000
    ABU([21])
    style ABU fill: #CCFFCC, color: #000000
    ABY([22])
    style ABY fill: #CCFFCC, color: #000000
    ABc([23])
    style ABc fill: #CCFFCC, color: #000000
    AAA --> AAE
    AAA --> AAI
    AAA --> AAM
    AAE --> AAI
    AAE --> AAM
    AAI --> AAM
    AAQ --> AAU
    AAQ --> ABc
    AAQ --> AA4
    AAU --> AAY
    AAU --> AAw
    AAY --> AAc
    AAY --> AAo
    AAc --> AAg
    AAc --> ABc
    AAg --> AAk
    AAg --> ABU
    AAk --> AAo
    AAk --> ABM
    AAo --> AAs
    AAs --> AAw
    AAs --> ABI
    AAw --> AA0
    AA0 --> AA4
    AA0 --> ABE
    AA4 --> AA8
    AA8 --> ABA
    AA8 --> ABY
    ABA --> ABE
    ABA --> ABQ
    ABE --> ABI
    ABI --> ABM
    ABM --> ABQ
    ABQ --> ABU
    ABU --> ABY
    ABY --> ABc

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

networkx_mermaid-0.3.0.tar.gz (12.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

networkx_mermaid-0.3.0-py3-none-any.whl (8.2 kB view details)

Uploaded Python 3

File details

Details for the file networkx_mermaid-0.3.0.tar.gz.

File metadata

  • Download URL: networkx_mermaid-0.3.0.tar.gz
  • Upload date:
  • Size: 12.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for networkx_mermaid-0.3.0.tar.gz
Algorithm Hash digest
SHA256 32ef3924a6946b3fe0434455b80aac6ebaa3154f7675e595b049f51834e2d468
MD5 54d6330966ce88d53cd15d2a5ca80966
BLAKE2b-256 818672096979049933633e6f4c0a48631d3f6ca8e2b7a29eff5e5a828c3d59a9

See more details on using hashes here.

File details

Details for the file networkx_mermaid-0.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for networkx_mermaid-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0a923b569a29f71e227d620f352ef834ebe25d43bc15e47676db0b365483197d
MD5 70f5e2aa0224e878343b60a36b0a2ea9
BLAKE2b-256 07ae2360ef2391fb27ca92990f982971d74996c2a2870521dd79b6f346b33180

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page