问题
I am trying to make colored graphs. I keep running into odd behavior.
I cannot get the colormap to assign colors automatically to the nodes. All nodes I try to do this with wind up the same color!
The floats are the colors that are supposed to be assigned to the 6 nodes. Two of the 7 floats are the same because it is a cycle.
When I manually specify the color of the nodes (node_color=['r']
, etc.) it works fine, not only for the root (in red), but for the nodes in the cycle as well.
Code:
t=0
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
#MAKE
G.add_node("ROOT")
#make all others
for i in x:
for ct,j in enumerate(i):
G.add_node(j[t] )
if ct ==0:
G.add_edge("ROOT", j[t])
else:
G.add_edge(i[ct-1][t], i[ct][t])
nx.write_dot(G,'g')
#DRAW
pos=nx.graphviz_layout(G,prog='neato')
nx.draw_networkx_nodes(G,pos, nodelist=['ROOT'], node_color=['r'])
#draw all others
for i in x:
for ct,j in enumerate(i):
print CD[j[t]]#, np.around([CD[j[t]]],decimals=2)
nx.draw_networkx_nodes(G,pos, nodelist = [j[t]], cmap=plt.get_cmap('Set3') ,node_color=np.around([CD[j[t]]],decimals=2))#float(c) for c in nodecolors(x[i],1)] )
nx.draw_networkx_edges(G, pos,arrows=True)
#Display properties
limits=plt.axis('off')
Here, x
is an array of node names, and CD
is a dictionary mapping names to floats. For completeness, here they are:
x = [[(1.000004+0j)], [(-0.5000065+0.86602454j)], [(-0.5000065-0.86602454j)],[(1.000004+0j)],[(-0.5000065+0.86602454j)],[(-0.5000065-0.86602454j)]]
CD = {(-0.50000649677999998-0.8660245358880001j): 0.7142857142857143,
(-0.50000649677999998+0.8660245358880001j): 0.5714285714285714,
(-0.50000049676800007-0.86603492822400008j): 0.14285714285714285,
(-0.50000049676800007+0.86603492822400008j): 0.42857142857142855,
0j: 0.0,
(0.99999200001600019-0j): 0.8571428571428571,
(1.000004000004+0j): 0.2857142857142857}
Colormap functionality works for me in other cases so I have the feeling I am making a basic error. Any ideas?
回答1:
As this is old and Lack answered the question in the comments I am copying his answer here and accepting:
I can't run your code without errors (
TypeError: 'complex' object has no attribute '__getitem__' on j[t]
) but it's the same problem as your other question which I answered (stackoverflow.com/questions/27831022/…). Because you pass only one node at a time todraw_networkx_nodes
, it "normalizes" the length-1 array of colors without regard to the other nodes. You should get rid of the loop and pass all the nodes in one array todraw_networkx_nodes
.
来源:https://stackoverflow.com/questions/27871827/colormap-not-working-in-networkx