2

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

graph plot

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()
2
  • What's wrong with G2.add_nodes_from([spam.name, eggs.name]) G2.add_edge(spam.name, eggs.name)?
    – MathBio
    Jan 25, 2016 at 20:14
  • 1
    @MathBio The trouble is that the nodes are then the strings, not the Breakfast objects, and accessing the other attributes of a node object would require setting up an extra dictionary (and would restrict the names to be unique).
    – Calaf
    Jan 25, 2016 at 21:07

1 Answer 1

4

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

nodes as objects

4
  • @Calaf Maybe try to increase the node size. I suggest graph-tool which uses cairo to draw. But I don't understand, why my answer does not answer your question?
    – Kirell
    Jan 25, 2016 at 21:49
  • It does. I was hoping you also know a solution to the node_shape problem. :)
    – Calaf
    Jan 25, 2016 at 22:01
  • I already answered a similar question. The only way I know is to actually look at the source code, and create your own matplotlib drawing function. Overall, if you want to draw graphs, I suggest you don't use matplotlib. Maybe some interactive JS stuff like Sigma.js
    – Kirell
    Jan 25, 2016 at 22:05
  • 1
    If both __repr__ and __str__ methods are used, networkx will use __str__ method as label.
    – Bacara
    Nov 18, 2019 at 4:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.