Ankita
Ankita

Reputation: 485

Problem while constructing networkx graph

I have the following data in dataframe format

  a       b
-510    -350
-300    -120
-350    -170
-170     30
 30      210
-120     30
-690    -510

Using this data I am trying to construct networkx graph using python and so far written following codes

import networkx as nx

G1 = nx.DiGraph()
G1.add_edges_from(data)
data_1= nx.spring_layout(G1)

fig1=plt.figure(figsize=(5,2),dpi=300)
nx.draw(G1, data_1, node_size=1000, with_labels=True, node_color='y',vertex_label_size=100)

But getting following error Edge tuple start must be a 2-tuple or 3-tuple which is basically from adding edges. I tried some google search could not find any suitable answer to solve this. Could you please help me with this? thanks in advance.

Upvotes: 0

Views: 53

Answers (1)

yatu
yatu

Reputation: 88226

To build a graph from a pandas dataframe, you have nx.from_pandas_edgelist:

G1 = nx.from_pandas_edgelist(df, source='a', target='b', create_using=nx.DiGraph)
pos= nx.spring_layout(G1)

fig1=plt.figure(figsize=(5,2),dpi=300)
nx.draw(G1, pos, node_size=100, with_labels=True, node_color='y')

enter image description here

Upvotes: 1

Related Questions