Search code examples
pythonmatplotlibgraphnetworkx

Python networkx - How to draw graph with labels


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


Solution

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