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

时间:2016-01-25 19:56:42

标签: python networkx

使用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()

graph plot

如果节点是对象而不是字符串,我理解it's possible创建一个额外的字典并将其用于节点标签,但是是否可以直接使用对象成员(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()

1 个答案:

答案 0 :(得分:1)

添加一个简单的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()

nodes as objects