简体   繁体   中英

Labeling nodes in a networkx graph when nodes are objects

It's easy to label the nodes of a graph using 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()

图形图

If the nodes are objects rather than strings, I understand that it's possible to create an extra dictionary and use it for the node labels, but is it possible to use an object member ( name ) directly as the label?

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

Adding a simple repr method seems to do the trick:

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

节点作为对象

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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