Reputation: 423
Using Networkx, I am considering a graph that is in reality the union of several subgraphs. I am trying to figure out the best way to deal with this. Currently, I have been using the following strategy, but was wondering if someone had a better suggestions.
First I add the nodes one at a time, they are from a rectangular lattice with m rows and n columns, so it's fairly easy.
G=nx.Graph()
PN = set() #first set of nodes
DN = set() #second set of nodes
for i in range(m):
for j in range(n):
if <sorting criterion here>:
G.add_node(j + i *n, pos = <insert function of i and j here>,
node_type = 'type_1', node_color = 'b')
PN.add(j + i *n, pos = <insert function of i and j here> )
else:
G.add_node(j + i *n, pos = <insert function of i and j here>,
node_type = 'type_2', node_color = 'g')
DN.add(j + i *n, pos = <insert function of i and j here> )
pos = nx.get_node_attributes(G, 'pos')
nx.draw_networkx_nodes(G,pos,PN, node_color = 'b', node_size = 35)
nx.draw_networkx_nodes(G,pos,DN, node_color = 'g', node_size = 35)
I have tried, but it has failed, to do something similar that I think would be better. That idea is what follows:
G=nx.Graph()
V = set()
for i in range(m):
for j in range(n):
if <sorting criterion here>:
V.add(j + i *n, pos = <insert function of i and j here>,
node_type = 'type 1', node_color = 'b')
else:
V.add(j + i *n, pos = <insert function of i and j here>,
node_type = 'type 2', node_color = 'g')
color = nx.get_node_attributes(G,'node_color')
pos = nx.get_node_attributes(G, 'pos')
nx.draw_networkx_nodes(G,pos, color)
Unfortunately, "color" doesn't seem to work like "pos" does, and this latter method outputs all red nodes. Any suggestions would be greatly appreciated!
Upvotes: 0
Views: 379
Reputation: 25319
You are right - the 'node_color' parameter takes a single color or a list of colors (not a dictionary). So the simplest way is to use the same strategy as your first code snippet and draw the two groups of nodes separately.
If you want to just issue one call to nx.draw_networkx_nodes() the node_color parameter should have a list of colors with the same length as the list of nodes and in the same order. So you could do the following:
color = nx.get_node_attributes(G,'node_color')
pos = nx.get_node_attributes(G, 'pos')
nodelist,node_color = zip(*color.items())
nx.draw_networkx_nodes(G,pos, nodelist=nodelist, node_color=node_color)
Upvotes: 1