Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

How to show node name in graphs using networkx? [duplicate]

Writer Mia Lopez

I have the code

import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 1), (2, 3)])
nx.draw(G)
plt.savefig("graph.png")
plt.show()

And it draws the following graph:enter image description here

However, I need to display labels. How do I display the numeric values and words (one, two, three and four) within the nodes of the graph?

0

1 Answer

You just need to call the with_labels=True parameter with nx.Draw():

import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 1), (2, 3)])
nx.draw(G,with_labels=True)
plt.savefig("graph.png")
plt.show()

You can also call font_size, font_color, etc.

See the documentation here:

2