views:

207

answers:

1

I a using the networkx package of Python. The documentation says we can do H.add_edge(1,2,color='blue') but the output shows an edge with the default(black) color. When I do H.add_node(12,color='green') I get a new node with same default red color.

+2  A: 

Peter, according to the documentation, to change the color with which nodes/edges are drawn, you have to provide the node_color argument to the drawing function. I.e. from this example, to draw a graph like this (note different colors of nodes):

alt text

The code is:

#!/usr/bin/env python
"""
Draw a graph with matplotlib.
You must have matplotlib for this to work.
"""
__author__ = """Aric Hagberg ([email protected])"""
try:
    import matplotlib.pyplot as plt
except:
    raise

import networkx as nx

G=nx.house_graph()
# explicitly set positions
pos={0:(0,0),
     1:(1,0),
     2:(0,1),
     3:(1,1),
     4:(0.5,2.0)}

nx.draw_networkx_nodes(G,pos,node_size=2000,nodelist=[4])
nx.draw_networkx_nodes(G,pos,node_size=3000,nodelist=[0,1,2,3],node_color='b')
nx.draw_networkx_edges(G,pos,alpha=0.5,width=6)
plt.axis('off')
plt.savefig("house_with_colors.png") # save as png
plt.show() # display

Note the node_color argument to the second call to draw_networkx_nodes. Does this help?

Eli Bendersky
I am building a graph of 100 nodes. Do I need to set the pos of every node? Can I set it at random? How do I do that
Bruce
@Peter: do the colors work and this is a different question? Anyhow, I'm not an expert on the drawing stuff in networkx. It does has a layout engine you can use to automatically draw large graps, read the documentation and see the examples - I'm sure you'll figure it out
Eli Bendersky
Yes the colors work. I found the layout from the documentation. Thanks Eli
Bruce