pydot: is it possible to plot two different nodes with the same string in them?

岁酱吖の 提交于 2019-12-05 03:36:21

Your nodes always need a unique names, otherwise you cannot name them uniquely to attach edges between them. However, you can give each node a label, which is what is displayed when rendered.

So you'll need to add nodes with unique ids:

graph = pydot.Dot(graph_type='graph')
graph.add_node(pydot.Node('literal_0_0', label='0'))
graph.add_node(pydot.Node('literal_0_1', label='0'))
graph.add_node(pydot.Node('literal_1_0', label='1'))
graph.add_node(pydot.Node('literal_1_1', label='1'))

then add graph edges connecting those nodes:

edge = pydot.Edge("a_2>10", "literal_0_0")
graph.add_edge(edge)
edge = pydot.Edge("a_2>10", "literal_1_0")
graph.add_edge(edge)
edge = pydot.Edge("a_3>-7", "literal_0_1")
graph.add_edge(edge)
edge = pydot.Edge("a_3>-7", "literal_1_1")
graph.add_edge(edge)

Together with the rest of the edges you defined this makes:

The "canonical" answer is to use the uuid module from the standard library, as networkx does here.

This is better than using id to create node names for pydot that correspond to the nodes in your original graph, because if (in theory) a node object gets deleted while you are building your pydot graph, then that id won't necessarily be unique. In contrast, the UUID objects created are unique, persistent and independent of the lifespan of the original nodes.

However for this to happen, something very weird must be going on while you create the pydot graph, which is rather unlikely. The advantage of using id is that you don't need to build and pass around a mapping from original nodes to UUID objects (so that you construct consistently the edges after adding the nodes).

One interesting case are nested graphs: two different graphs may contain the same hashable object in networkx (say a), then id cannot be used any more directly on the node. But in that case, id can still be used, by combining the (node, graph) pair as: str(id(node)) + str(id(graph)).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!