Brahim Gaabab
Brahim Gaabab

Reputation: 310

How to get nodes coordinates in graph rendered with graphviz

I'm implementing a stepwise graph transformation algorithm where nodes are removed or added in each step and want to keep a trace of all the intermediate graphs as images files where a node keeps rendered at the same position until removed. This will help make a final animation.

I thought about getting the nodes positions from the initial step as computed by the layout engine and then pass them as a node attribute for next steps.

I'm using the graphviz library, but I could not find any way to get the nodes coordinates (pos attribute) in the rendered graphs. Here is a code excerpt.

    from graphviz import Digraph
    dot = Digraph()
    dot.node('x', label='hello')
    dot.node('y', label='world')
    dot.edge('x', 'y')
    dot.render(filename='hello.gv', view=True, cleanup=False)

I also inspected the dot object, but found nothing. Am I missing some thing? I could not conform whether positions are exported via the API or no. In this case, which different library can help?

Upvotes: 8

Views: 2250

Answers (1)

Rashedkoutayni
Rashedkoutayni

Reputation: 51

First of all, you need to pipe and decode your Digraph object to JSON format. Afterwards, you can convert the JSON string to a JSON object and parse it:

# import JSON parser
import json

# decode the Digraph to JSON format
json_string = dot.pipe('json').decode()

# parse the resulting json_string
json_dict = json.loads(json_string)

# now, you have a JSON dictionary that has two relevant keys:
# 'objects' for nodes and 'edges' for, well, edges.
# you can iterate over the nodes and get the (x,y) position for each node as follows:
for obj in json_dict['objects']:
    print(obj['name'], '\t', obj['pos'])

I had to try each format in graphviz.FORMATS to find out the most suitable one.

I know it might be too late, but just in case you or anybody else needs the answer.

Upvotes: 4

Related Questions