2015-10-04 76 views
0

所以我有以下函數來繪製一個問題即時通訊工作。它基本上是一個關鍵的節點檢測問題或阻塞。我有一些值x,並決定攻擊節點z。基本上我想用正在處理/攻擊的活動和不活動節點和節點爲我的圖表着色。這是我到目前爲止。圖例爲networkx繪圖功能

DEF draw_solution(克,zsolution,xsolution,T,XMIN = 0,文件名= '檢驗.pdf'):

# draw solution 
pos = {n: ndata['coord'] for n,ndata in g.nodes_iter(data=True)} 
ncolour=[] 
for n,ndata in g.nodes_iter(data=True): 
    if ndata['fuel_load'] < xmin: 
     ncolour.append('gold') 
    else: 
     ncolour.append('yellowgreen') 
pp = PdfPages(filename) 
fig = plt.figure(figsize=(11.7,8.3)) 
fig.suptitle('full graph and initial fuel load') 
plt.axis('off') 
nx.draw_networkx(g, pos, font_size=9, node_color=ncolour) 
fig.savefig(pp, format='pdf') 
fig.clf() 

for t in range(T): 
    g_copy = g.copy() 
    #node colour 
    ncolour=[] 
    for i in g.nodes_iter(): 
     if zsolution[i,t] > 0.99: 
      ncolour.append('lightcoral') 
      #g_copy.remove_edges_from(g.edges(i)) 
     elif xsolution[i,t] < xmin: 
      ncolour.append('gold') 
      g_copy.remove_edges_from(g.edges(i)) 
     else: 
      ncolour.append('yellowgreen') 

    plt.axis('off') 
    fig.suptitle('t={}, before treatment'.format(t)) 
    nx.draw_networkx(g_copy, pos, font_size=9, node_color=ncolour, label=ncolour) 
    fig.savefig(pp, format='pdf') 
    fig.clf() 

    g_copy = g.copy() 
    #node colour 
    ncolour=[] 
    for i in g.nodes_iter(): 
     if zsolution[i,t] > 0.99: 
      ncolour.append('lightcoral') 
      g_copy.remove_edges_from(g.edges(i)) 
     elif xsolution[i,t] < xmin: 
      ncolour.append('gold') 
      g_copy.remove_edges_from(g.edges(i)) 
     else: 
      ncolour.append('yellowgreen') 

    plt.axis('off') 
    fig.suptitle('t={}, after treatment'.format(t)) 
    nx.draw_networkx(g_copy, pos, font_size=9, node_color=ncolour, label=ncolour) 
    fig.savefig(pp, format='pdf') 
    fig.clf() 

pp.close() 
fig.clf() 

出於某種原因,我不能得到圖例正確?

請幫忙!謝謝!

+0

你想發生什麼事情沒有發生? - 「傳說」是什麼意思? – Joel

+0

我想要一個對應於顏色的圖例。所以我想要像 lightcoral - 攻擊 黃金 - 活躍 yellowgreen - 無效 –

回答

3

這是你在追求什麼?

import networkx as nx 
import matplotlib.pyplot as plt 
G=nx.fast_gnp_random_graph(20,0.2) 

rednodes = [1,2,4,5] 
bluenodes = [10,12] 
greennodes=[3,6,9] 
yellowgreennodes = [node for node in G.nodes() if node not in rednodes+greennodes+bluenodes] 
pos = nx.spring_layout(G) 
nx.draw_networkx_nodes(G,pos=pos,nodelist=rednodes, node_color='red', label='red nodes') 
nx.draw_networkx_nodes(G,pos=pos,nodelist=bluenodes, node_color='blue', label='blue nodes') 
nx.draw_networkx_nodes(G,pos=pos,nodelist=greennodes, node_color='green', label='green nodes') 
nx.draw_networkx_nodes(G,pos=pos,nodelist=yellowgreennodes, node_color='yellowgreen', label='yellowgreen nodes') 
nx.draw_networkx_edges(G,pos=pos) 
plt.legend(numpoints = 1) 
plt.show() 

enter image description here

我不是它爲什麼傳說中的繪製多個點很清楚...我想numpoints=1將採取照顧。 編輯顯然這可以通過這個來處理:Setting numpoints in matplotlib legend does not work