如何使节点坐标与GraphViz呈现



我正在实现一种逐步图形变换算法,其中删除或在每个步骤中添加节点,并希望将所有中间图的跟踪作为图像文件,其中节点保持在呈现节点的情况下。相同的位置直到删除。这将有助于制作最终动画。

我考虑过从布局引擎计算的初始步骤中获取节点位置,然后将它们作为下一步的节点属性传递。

我正在使用GraphViz库,但是我找不到任何方法来获取渲染图中的节点坐标(pos属性(。这是代码摘录。

    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)

我还检查了dot对象,但没有发现。我错过了一些东西吗?我无法符合是否通过API导出的位置。在这种情况下,哪些不同的库可以提供帮助?

首先,您需要将Digraph对象输送并解码为JSON格式。之后,您可以将JSON字符串转换为JSON对象并将其解析:

# 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'])

我必须尝试GraphViz.Formats中的每种格式才能找出最合适的格式。

我知道这可能为时已晚,但是以防您或其他任何人都需要答案。

最新更新