Reputation: 197
I have two data frames that I am using to create a graph with networkx in Python. The dataframe df1(node coordinates) and df2(edge info), look as such:
location x y
0 The Wall 145 570
2 White Harbor 140 480
and
location x y
56 The Wall Winterfell 259
57 Winterfell White Harbor 247
This is the code I implemented to try and graph it:
plt.figure()
G=nx.Graph()
for i, x in enumerate(df1['location']):
G.add_node(x, pos=(df1['x'][i], df1['y'][i]))
for x, x2, w in zip(df2['location'], df2['x'], df2['y']):
G.add_edge(x, x2, weight=w)
plt.figure(figsize=(15,15))
pos = nx.get_node_attributes(G, 'pos')
weights = nx.get_edge_attributes(G, 'weight')
nx.draw(G, pos=pos, node_size=40, with_labels=True, fontsize=9)
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=weights)
plt.show()
I ran this a couple times before and it seemed to work, now however after re-opening jupyter notebook and running it again, it will not work. I mainly have two major issues.
nx.draw(G, pos=pos, node_size=40, with_labels=True, fontsize=9)
, my graph will show up, but no labels will be shown, even with with_labels set to true.nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=weights)
is now showing me the error can't multiply sequence by non-int of type 'float'I have been looking at this for a couple of hours and I can't seem to fix it, any thoughts?
Edit: I can get the labels to show up if a exclude pos=pos from nx.draw, but it will not work if I include it
Upvotes: 1
Views: 1472
Reputation: 88295
The problem is that you are not specifying any pos
attribute for the node Winterfell
, and then when you try to access it in draw_networkx_edge_labels
it doesn't find it.
If you try giving it a position attribute, say:
location x y
0 TheWall 145 570
1 Winterfell 142 520
2 WhiteHarbor 140 480
Then the attributes of all nodes can be correctly accessed and the network is corectly drawn:
plt.figure()
G=nx.Graph()
df1 = df1.reset_index(drop=True)
df2 = df2.reset_index(drop=True)
for i, x in enumerate(df1['location']):
G.add_node(x, pos=(df1.loc[i,'x'], df1.loc[i,'y']))
for x, x2, w in zip(df2['location'], df2['x'], df2['y']):
G.add_edge(x, x2, weight=w)
plt.figure(figsize=(15,15))
pos = nx.get_node_attributes(G, 'pos')
weights = nx.get_edge_attributes(G, 'weight')
nx.draw(G, pos=pos, node_size=40, with_labels=True, fontsize=9)
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=weights)
plt.show()
Upvotes: 1