0
$\begingroup$

I am now drawing a weighted directed graph using Pygraphviz.

The adjacency matrix A of the weighted directed graph is

A = pd.DataFrame({'X': [0.0,0.1,-0.8], 'Y': [-0.7,0.0,-0.1], 'Z': 
    [0.4,0,-0.1]} ,index=["X", "Y", "Z"])

A

where A_{i,j} indicates the edge weight from the node i to the node j.

I was able to draw the graph without edge color.

import networkx as nx
from networkx.drawing.nx_agraph import to_agraph
from IPython.display import SVG, display

G_nx = nx.from_pandas_adjacency(A,create_using=nx.DiGraph())
G_nx.graph['edge'] = {'arrowsize': '1.0', 'splines': 'curved'}
G_nx.graph['graph'] = {'scale': '3'}


Agraph_eg = to_agraph(G_nx)                                                              
Agraph_eg .node_attr["height"] = 0.3
Agraph_eg .node_attr["width"] = 0.3
Agraph_eg .node_attr["shape"] = "circle"
Agraph_eg .node_attr["fixedsize"] = "true"
Agraph_eg .node_attr["fontsize"] = 8
Agraph_eg.layout(prog="neato")                                                                     
Agraph_eg.draw('graph_eg1.png')

graph_eg1.png

But I have no idea how to assign edge colors and widths according to the following two rules.

#1 If weights are more than 0, edge color should be red. If weight are less than 0, edge color should be blue.

#2 Edge widths should be proportional to the absolute values of weights.

Do you have any idea how to do this??

$\endgroup$

1 Answer 1

2
$\begingroup$

This might help you

for edge in G_nx.edges(data=True):
    color = "black"
    weight = edge[2]["weight"]
    if weight > 0:
        color = "red"
    elif weight < 0:
        color = "blue"
    edge[2]["color"] = color
    edge[2]["penwidth"] = abs(weight)

This gives you the following graph:

enter image description here

Depending on your network size this solution might take some time. "penwidth" is the graphviz information for the edge width.

$\endgroup$
2
  • $\begingroup$ Thank you veru much !! It works !! $\endgroup$
    – Apppii092
    Oct 29, 2021 at 23:32
  • $\begingroup$ @Apppii092 if my answer solves your question could you please mark it as accepted? $\endgroup$
    – Mr_Z
    Oct 31, 2021 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.