Changing the color of edges in networkX

Viewed 761

I'm using networkX to plot graphs. and I want to change the color of a graph. I followed samples on the internet and following is my code:

def draw_graph():
    colors = []
    for i in range (nCount):
        for j in range (nCount):
            if ifActive(i,j,timeStep) == 1:
                colors.append("r")
                  
            else:
                colors.append("b")
                
    print ("colores = ", colors)                            
    color_map = []   
    nColor= nx.get_node_attributes(graph,'color')
    for nc in nColor:
        color_map.append(nColor[nc])
    nx.draw(graph,pos=nx.spring_layout(graph),edge_color = colors , node_color = color_map,with_labels = True )

but I am faced with the following error:

edge_color must be a color or list of one color per edge

How can I solve this error?

1 Answers

A simple solution to your problem is to use separated functions of networkx. Here is a simple example:

import networkx as nx
import matplotlib.pyplot as plt

graph = nx.erdos_renyi_graph(30,0.4)

options = ['r','b']
colors = []
for i in range(len(graph.edges())):
    if(i%2 == 0):
        colors.append(options[0])
    else:
        colors.append(options[1])

plt.figure(figsize=(10,10))
pos = nx.spring_layout(graph)
nx.draw_networkx_nodes(graph,pos=pos)
nx.draw_networkx_edges(graph,edge_color=colors,pos=pos)

Example of an ER network with different edge colors:
Example of an ER network with different edge colors

Edit: In your for loop you are considering two times the same edge. Try to change to the following:

for i in range (nCount):
    for j in range (0,i):
        if ifActive(i,j,timeStep) == 1:
            colors.append("r")
        else:
            colors.append("b")
Related