2015-01-10 15 views
1

我想製作彩色圖表。我不斷遇到奇怪的行爲。Colormap在NetworkX中不起作用

我無法讓顏色表自動將顏色分配給節點。我嘗試使用相同的顏色來完成所有節點!

enter image description here

浮子是本應該被分配到6個節點的顏色。七個花車中的兩個是相同的,因爲它是一個循環。

當我手動指定節點的顏色(node_color=['r']等)時,它工作正常,不僅對於根(紅色),而且對於循環中的節點也是如此。

代碼:

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')   

這裏,x是節點名稱的數組,並且CD是一個字典映射名稱浮動。爲了完整起見,在這裏,他們是:

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} 

顏色映射功能對我的作品在其他情況下,所以我有我想提出一個基本的錯誤感覺。有任何想法嗎?

+0

我不能沒有錯誤,運行代碼('類型錯誤:「複雜的」對象有沒有屬性'__getitem __'''上'j [t]'),但是它與我回答的其他問題是一樣的問題(http://stackoverflow.com/questions/27831022/drawing-colored-trees-with-networkx)。因爲一次只傳遞一個節點到'draw_networkx_nodes',所以它會對長度爲1的顏色數組進行「規格化」,而不考慮其他節點。您應該擺脫循環並將一個數組中的所有節點傳遞給'draw_networkx_nodes'。 – Lack

+0

我想你需要在'x'周圍放置一組括號來運行而不會出錯。我忘了那些。如果我設置了'vmax = 1'和'vmin = 0',它就會和*循環一起工作。 – Wapiti

+0

非常感謝您的幫助!我一直在爲此掙扎好幾天。 – Wapiti

回答

1

由於這是舊的,缺乏回答了這個問題的評論我在這裏複製他的答案和接受:

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 to draw_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 to draw_networkx_nodes .