Monday, June 27, 2022

[FIXED] How to define inner subgraphs in graphviz using python?

Issue

What

Is it possible, with using the graphivz lib, to write a subgraph inside another?

I tried

Using this API I tried to get to this image graph. It even came from that other question. That is, I know that it is possible, writing with pure language. However, I need to generate this graph automatically using python, for a state machine

Image:

enter image description here

Some code that i tried


Solution

You can use nested with clauses. Like this:

from graphviz import Graph

g = Graph('G', filename="example.gv")

with g.subgraph(name="cluster_outside1") as outside1:
    outside1.attr(label="outside 1")

    with outside1.subgraph(name="cluster_inside1") as inside1:
        inside1.attr(label="inside 1")
        inside1.node("a", "a")
        inside1.node("b", "b")
        inside1.edge("a", "b")

    with outside1.subgraph(name="cluster_inside2") as inside2:
        inside2.attr(label="inside 2")
        inside2.node("c", "c")
        inside2.node("d", "d")
        inside2.edge("c", "d")

with g.subgraph(name="cluster_outside2") as outside2:
    outside2.attr(label="outside 2")
    outside2.node("e", "e")
    outside2.node("f", "f")
    outside2.edge("e", "f")

g.view()

So, you need to add a subgraph calling the subgraph method by the parent graph



Answered By - Joao Albuquerque
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.