更新时间:2023-11-21 15:30:22
采用代码,图形不会按您期望的那样出现.如果您这样做:
Taking your code, your graph doesn't come out as you'd expect. If you do:
import pylab as p
import networkx as nx
G = nx.Graph()
G.add_edge("A","B")
G.add_edge("A","H")
G.add_edge("H","C")
G.add_edge("B","C")
G.add_edge("B","D")
nx.draw(G)
p.show()
您将看到以下图形:
you will see your graph as:
这是由于G.add_edge("A", "B")
的逻辑造成的:
This is due to the logic of G.add_edge("A", "B")
:
G
没有ID为"A"的节点,请添加它.G
没有ID为"B"的节点,请添加它.G
has no node of id "A", add it.G
has no node of id "B", add it.因此,您只能创建五个节点,而不是图片中的六个节点.
Thus, you only create five nodes, not six as in your picture.
修改 Networkx可以将任何可哈希值用作节点的值,并且在图中使用str(node)标记每个圆圈.因此,我们可以简单地定义我们自己的Node类(您可能想称其为Server?)并赋予其所需的行为.
Edit Networkx can take any hashable as value for a node, and in the graph it uses str(node) to label each circle. So we can simply define our own Node class (which you maybe want to call Server?) and give it the desired behavior.
import pylab as p
import networkx as nx
class Node(object):
nodes = []
def __init__(self, label):
self._label = label
def __str__(self):
return self._label
nodes = [Node(l) for l in ["A","B","C","C","D","H"]]
edges = [(0,1),(0,5),(5,2),(1,3),(1,4)]
G = nx.Graph()
for i,j in edges:
G.add_edge(nodes[i], nodes[j])
nx.draw(G)
p.show()
给我们 还有你想要的.
gives us and so what you wanted.