pydot:是否可以绘制两个带有相同字符串的不同节点? [英] pydot: is it possible to plot two different nodes with the same string in them?

查看:196
本文介绍了pydot:是否可以绘制两个带有相同字符串的不同节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pydot以便在python中绘制图形. 我想代表一个决策树,说一下(a1,a2,a3是属性,两个类分别是0和1:

I'm using pydot in order to draw graphs in python. I'd like to represent a decision tree, say something like (a1,a2,a3 are attributes and two classes are 0 and 1:

       a1>3
      /    \
  a2>10    a3>-7
   /  \     /  \
  1    0   1    0

但是,使用pydot只能创建两片叶子,并且树看起来像这样(附加的png):

However, using pydot, only two leaves are created and the tree looks like this (png attached):

       a1>3
      /    \
  a2>10    a3>-7
      |  X  |
      1     0

现在,在这种简单的情况下,逻辑还不错,但在较大的树中,属于不同分支的内部节点杂乱无章.

Now, in this simple case the logic is fine but in larger trees it is messy internal nodes belonging to different branches are unified.

我正在使用的简单代码是:

The simple code I'm using is:

import pydot
graph = pydot.Dot(graph_type='graph')
edge = pydot.Edge("a_1>3", "a_2>10")
graph.add_edge(edge)
edge = pydot.Edge("a_1>3", "a_3>-7")
graph.add_edge(edge)
edge = pydot.Edge("a_2>10", "1")
graph.add_edge(edge)
edge = pydot.Edge("a_2>10", "0")
graph.add_edge(edge)
edge = pydot.Edge("a_3>-7", "1")
graph.add_edge(edge)
edge = pydot.Edge("a_3>-7", "0")
graph.add_edge(edge)
graph.write_png('simpleTree.png')

我还尝试创建不同的节点对象,而不是创建边缘并将其添加到图形中,但是pydot似乎在节点池中检查具有相同名称的节点,而不是创建一个新节点.

I also tried creating different node objects than create the edges and than add it to the graph but it seems that pydot checks the node pool for nodes with the same name instead of creating a new one.

有什么想法吗?谢谢!

推荐答案

您的节点始终需要唯一的名称,否则您将无法唯一地命名它们以在它们之间附加边.但是,您可以为每个节点指定一个标签,该标签将在渲染时显示.

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.

因此,您需要添加具有唯一ID的节点:

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:

这篇关于pydot:是否可以绘制两个带有相同字符串的不同节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆