繁体   English   中英

当节点是对象时,在networkx图中标记节点

[英]Labeling nodes in a networkx graph when nodes are objects

使用networkx标记图的节点很容易

import networkx as nx
import matplotlib.pyplot as plt

G1 = nx.Graph()
a = "A"
b = "B"
G1.add_nodes_from([a, b])
G1.add_edge(a, b)
nx.draw_networkx(G1) # default with_labels=True
plt.show()

图形图

如果节点是对象而不是字符串,我知道可以创建一个额外的字典并将其用于节点标签,但是可以将对象成员( name )直接用作标签吗?

class Breakfast:
    def __init__(self, name):
        self.name = name

spam = Breakfast("Spam")
eggs = Breakfast("Eggs")
G2 = nx.Graph()
G2.add_nodes_from([spam, eggs])
G2.add_edge(spam, eggs)
nx.draw_networkx(G2, with_labels=True)
plt.show()

添加一个简单的repr方法似乎可以解决问题:

class Breakfast:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name

spam = Breakfast("Spam")
eggs = Breakfast("Eggs")
G2 = nx.Graph()
G2.add_nodes_from([spam, eggs])
G2.add_edge(spam, eggs)
nx.draw_networkx(G2, with_labels=True)
plt.show()

节点作为对象

暂无
暂无

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

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