0
from graphviz import *
import networkx as nx
from networkx import *
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_node(1)
G.add_node(2)
G.add_edge(1,2)
myLabels = {1: 'node1', 2: 'node2'}
nx.set_node_attributes(G, myLabels, 'label')
nx.draw(G,with_labels=True)

So current I use the latest networkx. When I use nx.draw(G, with_values=True), it uses the vertex indexes instead of labels.

How can I fix this? Thank you.

Image should say node1, node2

xxx
  • 1,153
  • 1
  • 11
  • 23
Duke Le
  • 332
  • 3
  • 14
  • 1
    Look at the second half of this answer: https://stackoverflow.com/a/28533293/2966723 – Joel Apr 24 '20 at 11:52

1 Answers1

1

Change this command: nx.draw(G,with_labels=True) to nx.draw(G,with_labels=True, labels = myLabels)

Joel
  • 22,598
  • 6
  • 69
  • 93
  • Can myLabels have more keys than the number of nodes in G.nodes() ? For example, myLabels = {1:'x1', 2:'x2', 3:'x3'} while G only has 2 nodes. When I do this, it gives KeyError due to myLabels – Duke Le Apr 24 '20 at 12:00