2017-02-15 33 views
0

我試圖用python的networkx繪製網絡。networkx:將網絡劃分爲兩種類型的節點

我有兩種類型的節點,這些類型的節點應該分開放置。我如何分別放置不同類型的節點?

作爲一個例子,請看下面的節點。

enter image description here

我想分開藍色節點(汽車,筆,紙,杯子),如下面的圖片紅色節點(狗,牛,貓)。

enter image description here

enter image description here

所以,我的問題是如何可以networkx繪製這些類型的網絡,類似的上述圖像節點的單獨的羣體?

作爲參考,我粘貼繪製第一幅圖像的代碼。

import networkx as nx 
import matplotlib.pyplot as plt 

G = nx.Graph() 
target_word_list = ["dog", "cow", "cat"] # represented by red nodes 
attribute_word_list = ["car", "pen","paper", "cup"] # represented by blue nodes 
word_list = target_word_list + attribute_word_list 

for i in range(0, len(word_list)): 
    G.add_node(i) 

pos=nx.spring_layout(G) # positions for all nodes 
# draw nodes 
nx.draw_networkx_nodes(G,pos, 
         nodelist=range(0, len(target_word_list)), 
         node_color='r', 
         node_size=50, alpha=0.8) 
nx.draw_networkx_nodes(G,pos, 
         nodelist=range(len(target_word_list), len(word_list)), 
         node_color='b', 
         node_size=50, alpha=0.8)  
labels = {} 
for idx, target_word in enumerate(target_word_list): 
    labels[idx] = target_word 
for idx, attribute_word in enumerate(attribute_word_list): 
    labels[len(target_word_list)+idx] = attribute_word 
nx.draw_networkx_labels(G,pos,labels,font_size=14) 

plt.axis('off') 

回答

1

您可以手動將某個組中的節點的y座標向上或向下移動。 所以,如果你有你的節點座標pos

for i in range(0, len(word_list)): 
    if word_list[i] in attribute_word_list: 
     pos[i][1] += 4 

這將在第二組拉昇的節點。

你的整個代碼:

import networkx as nx 
import matplotlib.pyplot as plt 

G = nx.Graph() 
target_word_list = ["dog", "cow", "cat"] # represented by red nodes 
attribute_word_list = ["car", "pen","paper", "cup"] # represented by blue nodes 
word_list = target_word_list + attribute_word_list 

for i in range(0, len(word_list)): 
    G.add_node(i) 

pos=nx.spring_layout(G) # positions for all nodes 

# if node is in second group, move it up 
for i in range(0, len(word_list)): 
    if word_list[i] in attribute_word_list: 
     pos[i][1] += 4 

# draw nodes 
nx.draw_networkx_nodes(G,pos, 
         nodelist=range(0, len(target_word_list)), 
         node_color='r', 
         node_size=50, alpha=0.8) 
nx.draw_networkx_nodes(G,pos, 
         nodelist=range(len(target_word_list), len(word_list)), 
         node_color='b', 
         node_size=50, alpha=0.8)  
labels = {} 
for idx, target_word in enumerate(target_word_list): 
    labels[idx] = target_word 
for idx, attribute_word in enumerate(attribute_word_list): 
    labels[len(target_word_list)+idx] = attribute_word 
nx.draw_networkx_labels(G,pos,labels,font_size=14) 

plt.axis('off') 
plt.show() 

輸出:

enter image description here