# In Pygraphviz, How can I assign edge colors according to edge weights?

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"])


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.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')


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??

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:

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

• Thank you veru much !! It works !! Oct 29 '21 at 23:32