1

I am trying to run the following code to plot networkx graph but it gives me type error: list indices must be integers or slices, not str. May you help me with that?

pos = [[6.886709112999999, 50.50618938]]
nodes = ['866','144']
edges = [['866', '144']]

G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
nx.draw_networkx(G, pos)
plt.show()

1 Answers1

1

If you want to specify the positions for draw_networkx you should supply a dictionary of positions (x,y):

pos (dictionary, optional) – A dictionary with nodes as keys and positions as values. If not specified a spring layout positioning will be computed. See networkx.drawing.layout for functions that compute node positions.

You can take a look here (how to plot a networkx graph using the (x,y) coordinates of the points list?) for a recent example. Or with your small example:

import networkx as nx
import matplotlib.pylab as plt

pos = {'866':[6.886709112999999, 0], '144': [50.50618938, 0]}
nodes = ['866','144']
edges = [['866', '144']]

G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
nx.draw_networkx(G, pos)
plt.show()

The type error you observed, is probably caused by networks trying to call your pos list with the nodes as index, e.g. pos['866'].

Sparky05
  • 4,692
  • 1
  • 10
  • 27