Take the 2-minute tour ×

I've written a simple code to generate a random walk in a given graph G using the networkx library.. Now, as i take the walk, I want the edges to get colored and drawn using matplotlib.. say in a loop. Eg: say i'm walking from node 1 to node 2 from a connecting edge, I want that edge to be colored differently from the rest. Heres the code:

def unweighted_random_walk(starting_point,ending_point, graph):
starting_point: String that represents the starting point in the graph
ending_point: String that represents the ending point in the graph
graph: A NetworkX Graph object
##Begin the random walk

#Determine the hitting time to get to an arbitrary neighbor of the
#starting point
while current_point!=ending_point:
    #pick one of the edges out of the starting_node with equal probs
return hitting_time
share|improve this question
add comment

2 Answers

Here's what I use:

def colors(G):
    colors = []
    for edge,data in G.edges_iter(data=True):
        # return a color string based on whatever property you want
        return 'red' if data['someproperty'] else 'blue'

        # alternatively you could store a 'color' key on the edge
        # return data['color']

    return colors

# When you invoke the draw command pass a list of edge colors
nx.draw_spectral(G, edge_color=colors(G))
share|improve this answer
add comment

This work fine... however, be careful to fill the list with the appropriate values. A modification to the code that works is:

def colors(G, attrib):
   colors = []    
   for node,data in G.nodes_iter(data=True):
     # return a color string based on whatever property you want
     if data['someproperty'] != attrib:
   return colors
share|improve this answer
add comment

Your Answer


