Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse the arrows in a Digraph using networkx?

I am trying to reverse the arrows of a Digraph, making the second column to be the parent. I am trying to use the nx.Digraph.reverse() method of networkx but it is giving me an error of TypeError: reverse() missing 1 required positional argument: 'self'. How can I make second column to be the parent node when there also has an attribute for the To value and a dictionary cannot hold the same key value so I cannot simply interchange the keys of the dictionary.

This is my code:

G=nx.from_pandas_edgelist(train, 'To', 'From',create_using=nx.DiGraph.reverse())

My dataframe is:

To    |    From   |  Category
A     |     A     |    0
B     |     A     |    0
C     |     A     |    0
D     |     F     |    1
E     |     F     |    1

The category is for the 'To' column. But when I try to use the Digraph it shows the 'To' value converging to the 'From' value. I want to make it such that it is diverging away from the 'From' value.

like image 569
Funky Avatar asked Nov 25 '25 21:11

Funky


1 Answers

nx.DiGraph.reverse() is expecting an instance of a graph. Instead set create_using to nx.DiGraph() to create directed graph from the edges of the dataframe and then reverse the direction of the edges:

G=nx.from_pandas_edgelist(df, 'To', 'From', create_using=nx.DiGraph())
nx.draw(G)

enter image description here

Now by doing as mentioned above:

G_rev = nx.DiGraph.reverse(G)
nx.draw(G_rev)

enter image description here

like image 51
yatu Avatar answered Nov 27 '25 11:11

yatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!