19

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?

macabeus
  • 4,156
  • 5
  • 37
  • 66

1 Answers1

37

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: https://networkx.github.io/documentation/latest/reference/drawing.html

Red
  • 26,798
  • 7
  • 36
  • 58
ryanmc
  • 1,821
  • 12
  • 14
  • 3
    Thank you! I was confused because I was following some [old manuals](http://www.python-course.eu/networkx.php), which this parameter did not appear. To show the number in word, I used `H = nx.relabel_nodes(G, {1: 'one', 2: 'two', 3: 'three', 4: 'four'})` and `nx.draw(H, with_labels=True)` – macabeus Oct 01 '15 at 18:27
  • Sorry I completely missed the last part regarding relabel – ryanmc Oct 01 '15 at 18:29