简体   繁体   English

Networkx和graphviz布局将节点放置在同一位置

[英]Networkx and graphviz layout placing nodes in same place

I'm using the networkx library to do some work with graphs and using matplotlib for visualising. 我正在使用networkx库对图形进行一些处理,并使用matplotlib进行可视化。

The problem I'm having is that the nodes are getting placed over each other. 我遇到的问题是节点之间相互放置。 I am using my own classes for the nodes - a simplified, runnable version shown here: 我正在为节点使用自己的类-此处显示的是一个简化的,可运行的版本:

import matplotlib
matplotlib.use('TKAgg')
import matplotlib.pyplot as plt
import networkx as nx

class MyCustomNode(object):
    def __init__(self, value):
    self.value = value

def __str__(self):
    return "val: " + self.value


graph = nx.Graph()
graph.add_edge(MyCustomNode('a'), MyCustomNode('b'))

labels = {}
for node in graph.nodes():
    labels[node] = str(node)

pos = nx.graphviz_layout(graph)
nx.draw(graph, pos, node_color='red', node_size=3000)
nx.draw_networkx_labels(graph, pos, labels, font_size=8, font_color='white')
plt.show()

这就是上面的代码显示的内容

What I've found is that the behaviour seems to what gets returned in the __str__ method. 我发现,该行为似乎是通过__str__方法返回的。 If I change the __str__ method to something where the starting is unique, it lays out as expected: 如果我将__str__方法更改为开头是唯一的内容,则其布局将按预期进行:

def __str__(self):
    return self.value 

在此处输入图片说明

Can't tell if this is the expected behaviour, or I'm doing something wrong, or this is a bug. 无法判断这是否是预期的行为,或者我做错了什么,或者这是一个错误。 Advice appreciated! 咨询表示赞赏! :) :)

Although I can't find an authoritative reference at the moment, here's what's going on: 尽管目前找不到权威的参考,但这是怎么回事:

Graphviz has some restrictions on what characters can appear in node names. Graphviz对节点名称中可以显示哪些字符有一些限制。 Among the characters it cannot handle is : . 在无法处理的字符中: So when everything was passed to graphviz, I believe it interpreted it as a single node whose name was just val (I may be wrong). 因此,当一切都传递给graphviz时,我相信它会将其解释为名称仅为val的单个节点(我可能错了)。

Then when networkx got the positions back from graphviz, it resulted in all the nodes being put in the same place. 然后,当networkx从graphviz获得位置时,导致所有节点都放在同一位置。

So your simplest option is to remove the colon. 因此,最简单的选择是删除冒号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM