networkx-mermaid


Namenetworkx-mermaid JSON
Version 0.2.1 PyPI version JSON
download
home_pageNone
SummaryCreate a Mermaid graph from a NetworkX graph
upload_time2025-08-31 13:07:56
maintainerNone
docs_urlNone
authorNone
requires_python>=3.10
licenseNone
keywords graph mermaid networkx
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            # networkx-mermaid

> Create a Mermaid graph from a NetworkX graph

[![codecov](https://codecov.io/gh/erivlis/networkx-mermaid/graph/badge.svg?token=lwajrOGQ8o)](https://codecov.io/gh/erivlis/networkx-mermaid)
[![Codacy Badge](https://app.codacy.com/project/badge/Coverage/f0d3c12c51d2484eb8f92e9f29615def)](https://app.codacy.com/gh/erivlis/networkx-mermaid/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_coverage)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/2d6220d81d1a48cba762842eb88fee41)](https://app.codacy.com/gh/erivlis/networkx-mermaid?utm_source=github.com&utm_medium=referral&utm_content=erivlis/networkx-mermaid&utm_campaign=Badge_Grade)
[![CodeFactor](https://www.codefactor.io/repository/github/erivlis/networkx-mermaid/badge)](https://www.codefactor.io/repository/github/erivlis/networkx-mermaid)
[![DeepSource](https://app.deepsource.com/gh/erivlis/networkx-mermaid.svg/?label=active+issues&show_trend=true&token=CA0lpqHi7MBnUi3L3AIDlEsJ)](https://app.deepsource.com/gh/erivlis/networkx-mermaid/)
[![DeepSource](https://app.deepsource.com/gh/erivlis/networkx-mermaid.svg/?label=resolved+issues&show_trend=true&token=CA0lpqHi7MBnUi3L3AIDlEsJ)](https://app.deepsource.com/gh/erivlis/networkx-mermaid/)

[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=erivlis_networkx-mermaid&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=erivlis_networkx-mermaid)
[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=erivlis_networkx-mermaid&metric=bugs)](https://sonarcloud.io/summary/new_code?id=erivlis_networkx-mermaid)
[![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=erivlis_networkx-mermaid&metric=code_smells)](https://sonarcloud.io/summary/new_code?id=erivlis_networkx-mermaid)
[![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=erivlis_networkx-mermaid&metric=duplicated_lines_density)](https://sonarcloud.io/summary/new_code?id=erivlis_networkx-mermaid)

[![Snyk](https://snyk.io/test/github/erivlis/networkx-mermaid/badge.svg)](https://snyk.io/test/github/erivlis/networkx-mermaid)

![Test](https://github.com/erivlis/networkx-mermaid/actions/workflows/test.yml/badge.svg)
![Test](https://github.com/erivlis/networkx-mermaid/actions/workflows/test-beta.yml/badge.svg)
![Test](https://github.com/erivlis/networkx-mermaid/actions/workflows/publish.yml/badge.svg)

<a href="https://www.jetbrains.com/pycharm/"><img alt="PyCharm" src="https://img.shields.io/badge/PyCharm-FCF84A.svg?logo=PyCharm&logoColor=black&labelColor=21D789&color=FCF84A"></a>
<a href="https://github.com/astral-sh/uv"><img alt="uv" src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json" style="max-width:100%;"></a>
<a href="https://github.com/astral-sh/ruff"><img alt="ruff" src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json" style="max-width:100%;"></a>
<a href="https://hatch.pypa.io"><img alt="Hatch project" class="off-glb" loading="lazy" src="https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg"></a>

## Example

```python title="Create a Mermaid Diagram from a NetworkX Graph"
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

```mermaid
---
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
```
            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "networkx-mermaid",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "Graph, Mermaid, NetworkX",
    "author": null,
    "author_email": "Eran Rivlis <eran@rivlis.info>",
    "download_url": "https://files.pythonhosted.org/packages/21/81/5653afd51008b7cb758cd8ae1bc9352e84843825404f7ddad3c529816beb/networkx_mermaid-0.2.1.tar.gz",
    "platform": null,
    "description": "# networkx-mermaid\n\n> Create a Mermaid graph from a NetworkX graph\n\n[![codecov](https://codecov.io/gh/erivlis/networkx-mermaid/graph/badge.svg?token=lwajrOGQ8o)](https://codecov.io/gh/erivlis/networkx-mermaid)\n[![Codacy Badge](https://app.codacy.com/project/badge/Coverage/f0d3c12c51d2484eb8f92e9f29615def)](https://app.codacy.com/gh/erivlis/networkx-mermaid/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_coverage)\n[![Codacy Badge](https://api.codacy.com/project/badge/Grade/2d6220d81d1a48cba762842eb88fee41)](https://app.codacy.com/gh/erivlis/networkx-mermaid?utm_source=github.com&utm_medium=referral&utm_content=erivlis/networkx-mermaid&utm_campaign=Badge_Grade)\n[![CodeFactor](https://www.codefactor.io/repository/github/erivlis/networkx-mermaid/badge)](https://www.codefactor.io/repository/github/erivlis/networkx-mermaid)\n[![DeepSource](https://app.deepsource.com/gh/erivlis/networkx-mermaid.svg/?label=active+issues&show_trend=true&token=CA0lpqHi7MBnUi3L3AIDlEsJ)](https://app.deepsource.com/gh/erivlis/networkx-mermaid/)\n[![DeepSource](https://app.deepsource.com/gh/erivlis/networkx-mermaid.svg/?label=resolved+issues&show_trend=true&token=CA0lpqHi7MBnUi3L3AIDlEsJ)](https://app.deepsource.com/gh/erivlis/networkx-mermaid/)\n\n[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=erivlis_networkx-mermaid&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=erivlis_networkx-mermaid)\n[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=erivlis_networkx-mermaid&metric=bugs)](https://sonarcloud.io/summary/new_code?id=erivlis_networkx-mermaid)\n[![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=erivlis_networkx-mermaid&metric=code_smells)](https://sonarcloud.io/summary/new_code?id=erivlis_networkx-mermaid)\n[![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=erivlis_networkx-mermaid&metric=duplicated_lines_density)](https://sonarcloud.io/summary/new_code?id=erivlis_networkx-mermaid)\n\n[![Snyk](https://snyk.io/test/github/erivlis/networkx-mermaid/badge.svg)](https://snyk.io/test/github/erivlis/networkx-mermaid)\n\n![Test](https://github.com/erivlis/networkx-mermaid/actions/workflows/test.yml/badge.svg)\n![Test](https://github.com/erivlis/networkx-mermaid/actions/workflows/test-beta.yml/badge.svg)\n![Test](https://github.com/erivlis/networkx-mermaid/actions/workflows/publish.yml/badge.svg)\n\n<a href=\"https://www.jetbrains.com/pycharm/\"><img alt=\"PyCharm\" src=\"https://img.shields.io/badge/PyCharm-FCF84A.svg?logo=PyCharm&logoColor=black&labelColor=21D789&color=FCF84A\"></a>\n<a href=\"https://github.com/astral-sh/uv\"><img alt=\"uv\" src=\"https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json\" style=\"max-width:100%;\"></a>\n<a href=\"https://github.com/astral-sh/ruff\"><img alt=\"ruff\" src=\"https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json\" style=\"max-width:100%;\"></a>\n<a href=\"https://hatch.pypa.io\"><img alt=\"Hatch project\" class=\"off-glb\" loading=\"lazy\" src=\"https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg\"></a>\n\n## Example\n\n```python title=\"Create a Mermaid Diagram from a NetworkX Graph\"\nimport threading\nimport webbrowser\nfrom tempfile import TemporaryDirectory\n\nimport networkx as nx\nimport networkx_mermaid as nxm\n\n\n# An example of a graph with multiple components\ndef create_graph():\n    pastel_colors = [\"#FFCCCC\", \"#CCFFCC\", \"#CCCCFF\", \"#FFFFCC\", \"#CCFFFF\", \"#FFCCFF\"]\n    graphs: list[nx.Graph] = [nx.tetrahedral_graph(), nx.dodecahedral_graph()]\n\n    for i, g in enumerate(graphs):\n        nx.set_node_attributes(g, {n: {\"color\": pastel_colors[i]} for n in g.nodes})\n\n    graph: nx.Graph = nx.disjoint_union_all(graphs)\n\n    graph.name = \" + \".join(g.name for g in graphs)\n\n    return graph\n\n\ndef create_builder():\n    # Create a Mermaid Diagram Builder with custom settings\n\n    builder = nxm.builders.DiagramBuilder(\n        orientation=nxm.DiagramOrientation.LEFT_RIGHT,\n        node_shape=nxm.DiagramNodeShape.ROUND_RECTANGLE,\n    )\n    return builder\n\n\ndef create_server(port: int, root_directory: str, open_browser: bool = True) -> threading.Thread:\n    import http.server\n    import socketserver\n\n    url = f\"http://localhost:{port}\"\n\n    class Handler(http.server.SimpleHTTPRequestHandler):\n        def __init__(self, *args, **kwargs):\n            super().__init__(*args, directory=root_directory, **kwargs)\n\n    def serve():\n        with socketserver.TCPServer(('', port), Handler) as httpd:\n            print(\"Serving at:\", url)\n            httpd.serve_forever()\n\n    server_thread = threading.Thread(target=serve)\n    server_thread.daemon = True\n    server_thread.start()\n\n    if open_browser:\n        webbrowser.open(url)\n\n\ndef main():\n    graph = create_graph()\n    builder = create_builder()\n\n    # Build the Mermaid Diagram\n    mermaid_diagram: nxm.typing.MermaidDiagram = builder.build(graph)\n\n    # Format the Mermaid Diagram for Markdown embedding\n    markdown_diagram: str = nxm.formatters.markdown(mermaid_diagram)\n\n    # or as single page HTML\n    html_diagram: str = nxm.formatters.html(mermaid_diagram, title=graph.name)\n\n    print('Mermaid Diagram:')\n    print(mermaid_diagram)\n    print(markdown_diagram)\n    print(html_diagram)\n\n    ## Save the HTML diagram to a file and serve it\n    with TemporaryDirectory() as temp_dir:\n        with open(f\"{temp_dir}/index.html\", 'w') as f:\n            f.write(html_diagram)\n\n        # Serve the HTML diagram\n        create_server(port=8073, root_directory=temp_dir, open_browser=True)\n\n        # Keep the main thread alive to allow the server to run\n        try:\n            while True:\n                pass\n        except KeyboardInterrupt:\n            print(\"Server stopped\")\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n## Example Output Diagram\n\n```mermaid\n---\ntitle: Platonic Tetrahedral Graph + Dodecahedral Graph\nconfig:\n  layout: dagre\n  look: neo\n  theme: neutral\n---\ngraph LR\n    AAA([0])\n    style AAA fill: #FFCCCC, color: #000000\n    AAE([1])\n    style AAE fill: #FFCCCC, color: #000000\n    AAI([2])\n    style AAI fill: #FFCCCC, color: #000000\n    AAM([3])\n    style AAM fill: #FFCCCC, color: #000000\n    AAQ([4])\n    style AAQ fill: #CCFFCC, color: #000000\n    AAU([5])\n    style AAU fill: #CCFFCC, color: #000000\n    AAY([6])\n    style AAY fill: #CCFFCC, color: #000000\n    AAc([7])\n    style AAc fill: #CCFFCC, color: #000000\n    AAg([8])\n    style AAg fill: #CCFFCC, color: #000000\n    AAk([9])\n    style AAk fill: #CCFFCC, color: #000000\n    AAo([10])\n    style AAo fill: #CCFFCC, color: #000000\n    AAs([11])\n    style AAs fill: #CCFFCC, color: #000000\n    AAw([12])\n    style AAw fill: #CCFFCC, color: #000000\n    AA0([13])\n    style AA0 fill: #CCFFCC, color: #000000\n    AA4([14])\n    style AA4 fill: #CCFFCC, color: #000000\n    AA8([15])\n    style AA8 fill: #CCFFCC, color: #000000\n    ABA([16])\n    style ABA fill: #CCFFCC, color: #000000\n    ABE([17])\n    style ABE fill: #CCFFCC, color: #000000\n    ABI([18])\n    style ABI fill: #CCFFCC, color: #000000\n    ABM([19])\n    style ABM fill: #CCFFCC, color: #000000\n    ABQ([20])\n    style ABQ fill: #CCFFCC, color: #000000\n    ABU([21])\n    style ABU fill: #CCFFCC, color: #000000\n    ABY([22])\n    style ABY fill: #CCFFCC, color: #000000\n    ABc([23])\n    style ABc fill: #CCFFCC, color: #000000\n    AAA --> AAE\n    AAA --> AAI\n    AAA --> AAM\n    AAE --> AAI\n    AAE --> AAM\n    AAI --> AAM\n    AAQ --> AAU\n    AAQ --> ABc\n    AAQ --> AA4\n    AAU --> AAY\n    AAU --> AAw\n    AAY --> AAc\n    AAY --> AAo\n    AAc --> AAg\n    AAc --> ABc\n    AAg --> AAk\n    AAg --> ABU\n    AAk --> AAo\n    AAk --> ABM\n    AAo --> AAs\n    AAs --> AAw\n    AAs --> ABI\n    AAw --> AA0\n    AA0 --> AA4\n    AA0 --> ABE\n    AA4 --> AA8\n    AA8 --> ABA\n    AA8 --> ABY\n    ABA --> ABE\n    ABA --> ABQ\n    ABE --> ABI\n    ABI --> ABM\n    ABM --> ABQ\n    ABQ --> ABU\n    ABU --> ABY\n    ABY --> ABc\n```",
    "bugtrack_url": null,
    "license": null,
    "summary": "Create a Mermaid graph from a NetworkX graph",
    "version": "0.2.1",
    "project_urls": {
        "Bug Tracker": "https://github.com/erivlis/networkx-mermaid/issues",
        "Documentation": "https://github.com/erivlis/networkx-mermaid",
        "Homepage": "https://github.com/erivlis/networkx-mermaid",
        "Source": "https://github.com/erivlis/networkx-mermaid"
    },
    "split_keywords": [
        "graph",
        " mermaid",
        " networkx"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "c6160c1402acafacc4135a06d8ff5857f83ca55e5ed8f9b199473d541510a686",
                "md5": "c9dc5328186c76cf380a687ae89d2ec9",
                "sha256": "5c4c6274488c0b8e5f9f79e4a192372201ae4c2d204b659805c7ea15f210a156"
            },
            "downloads": -1,
            "filename": "networkx_mermaid-0.2.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c9dc5328186c76cf380a687ae89d2ec9",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 8076,
            "upload_time": "2025-08-31T13:07:55",
            "upload_time_iso_8601": "2025-08-31T13:07:55.558176Z",
            "url": "https://files.pythonhosted.org/packages/c6/16/0c1402acafacc4135a06d8ff5857f83ca55e5ed8f9b199473d541510a686/networkx_mermaid-0.2.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "21815653afd51008b7cb758cd8ae1bc9352e84843825404f7ddad3c529816beb",
                "md5": "4dc51b7206a3145ec22c4286aff6bed1",
                "sha256": "fc6d3e810221aa805f64f0522618c0cbe46a51d821fab405e66e622e25bc38fd"
            },
            "downloads": -1,
            "filename": "networkx_mermaid-0.2.1.tar.gz",
            "has_sig": false,
            "md5_digest": "4dc51b7206a3145ec22c4286aff6bed1",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 12527,
            "upload_time": "2025-08-31T13:07:56",
            "upload_time_iso_8601": "2025-08-31T13:07:56.598700Z",
            "url": "https://files.pythonhosted.org/packages/21/81/5653afd51008b7cb758cd8ae1bc9352e84843825404f7ddad3c529816beb/networkx_mermaid-0.2.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-31 13:07:56",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "erivlis",
    "github_project": "networkx-mermaid",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "networkx-mermaid"
}
        
Elapsed time: 2.71388s