目前,我正试图使用NetworkX显示泛型Node类的对象之间的关系。由于两个节点之间有多个边是可能的,所以我尝试使用MultiGraph来实现这一点。我创建的node类包含一个名为“The”的属性,我希望将其显示在节点的顶部。每个节点还具有属性"id",该属性是该节点唯一的数字。但是,具有相同标题的多个节点会引发问题。在本例中,我希望节点Y和Z各自连接到称为"A“和"B”的新节点。注意,有两个节点名为"A“,两个节点名为"B”。我想象这样的样子:

以下代码生成一个图像,其中称为A和B的节点被视为每个节点仅为一个节点:
import networkx as nx
import matplotlib.pyplot as plt
# define Node class
class Node:
def __init__(self, caption, id, parent_id, parent_connections, children):
self.caption = caption
self.id = id
self.parent_id = parent_id
self.parent_connections = parent_connections
self.children = children
G = nx.MultiGraph()
# create all nodes for the example
node_x = Node(caption="X", id=1, parent_id=None, parent_connections=[], children=[])
node_y = Node(caption="Y", id=2, parent_id=1, parent_connections=["first connection"], children=[])
node_z = Node(caption="Z", id=3, parent_id=1, parent_connections=["first connection"], children=[])
node_a_y = Node(caption="A", id=4, parent_id=2, parent_connections=["first connection", "second connection", "third connection"], children=[])
node_b_y = Node(caption="B", id=5, parent_id=2, parent_connections=["first connection"], children=[])
node_a_z = Node(caption="A", id=6, parent_id=3, parent_connections=["first connection"], children=[])
node_b_z = Node(caption="B", id=7, parent_id=3, parent_connections=["first connection"], children=[])
all_nodes = [node_x, node_y, node_z, node_a_y, node_b_y, node_a_z, node_b_z]
# fill the children lists with every node's children
for node in all_nodes:
for other_node in all_nodes:
if other_node is not node and other_node.parent_id == node.id:
node.children.append(other_node)
# add the nodes and edges to the MultiGraph G
for node in all_nodes:
G.add_node(node.caption)
for child in node.children:
for i in range(0, len(child.parent_connections)):
G.add_edge(node.caption, child.caption, length=10)
# draw the Graph
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_color="r", node_size=100, alpha=1)
ax = plt.gca()
for e in G.edges:
ax.annotate(e[1],
xy=pos[e[0]], xycoords="data",
xytext=pos[e[1]], textcoords="data",
arrowprops=dict(arrowstyle="-", color="0.5",
shrinkA=5, shrinkB=5,
patchA=None, patchB=None,
connectionstyle="arc3,rad=rrr".replace("rrr",str(0.3*e[2])),
),
)
plt.axis('off')
plt.show()

此外,将节点对象直接添加到G的节点和边缘,而不仅仅是添加标题,就会产生这样的结果:

这似乎是我正在寻找的,但不幸的是,对象本身被用作标题而不是标题属性。是否有一种使networkx使用给定对象的某个属性作为标题的方法?如果没有,我还能做些什么来达到我的目标?
发布于 2022-06-17 15:23:33
节点需要有不同的(和可理解的)ID。默认情况下,networkx使用这些ID作为节点的标签。但是,可以使用labels属性指定其他标签。labels值可以具有重复项(与节点ID不同)。
nx.draw(nx.Graph([(0, 1)], labels={0 : 'a', 1 : 'a'}); plt.show()

另见:nx.draw_networkx_labels。
关于你问题的第二部分:
,但不幸的是,对象本身被用作标题,而不是标题属性。
准确地说,您的__repr__类的Node方法用于节点标签。
是否有一种使networkx使用给定对象的某个属性作为标题的方法?
您可以重写默认的__repr__方法来返回标题属性。
class Node:
def __init__(self, ...):
...
def __repr__(self):
return self.captionhttps://stackoverflow.com/questions/72548467
复制相似问题