2017-02-15 14 views
0

私は、pythonのnetworkxでネットワークを描こうとしています。networkx:2つのタイプのノードを分けるようにネットワークを描画します。

私は2つのタイプのノードを持っており、それらのタイプのノードは別々に置かなければなりません。異なるタイプのノードを別々に置くにはどうしたらいいですか?

例として、以下のノードを参照してください。

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

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

関連する問題