2017-09-15 88 views
0

我正在研究一個屬於兩種類型的小例子節點集{'human', 'machine'},我想在字典形式中標記節點屬性,在networkx圖中的每個節點之外,如節點c, e,j在下面的圖表中。 (我使用的MS Word添加圖表上的字典類型屬性):使用下面的代碼生成在節點外部標記networkx節點屬性

enter image description here

基部情節:

import networkx as nx 
G = nx.Graph() 
G.add_nodes_from(['a', 'b', 'c', 'd', 'e', 'f', 'g'], type = 'machine') 
G.add_nodes_from(['h', 'i', 'j'], type = 'human') 
G.add_edges_from([('a', 'c'), ('a', 'b'), ('a', 'd'), ('a', 'f'), ('b', 'd'), ('b', 'e'), ('b', 'g'), ('c', 'f'), ('c', 'd'), ('d', 'f'), ('d', 'e'), ('d', 'g'), ('e', 'g'), ('f', 'g'), ('f', 'h'), ('g', 'h'), ('h', 'i'), ('i', 'j')]) 

def plot_graph(G, weight_name=None): 
    import matplotlib.pyplot as plt 

    plt.figure() 
    pos = nx.spring_layout(G) 
    edges = G.edges() 
    weights = None 

    if weight_name: 
     weights = [int(G[u][v][weight_name]) for u,v in edges] 
     labels = nx.get_edge_attributes(G,weight_name) 
     nx.draw_networkx_edge_labels(G,pos,edge_labels=labels) 
     nx.draw_networkx(G, pos, edges=edges, width=weights); 
    else: 
     nx.draw_networkx(G, pos, edges=edges); 

plot_graph(G, weight_name=None) 
plt.savefig('example.png') 
plt.show() 

但這裏的問題是,

nx.get_node_attributes()nx.draw_networkx_labels()函數不會在標籤上包含字典關鍵字(在本例中爲'type')(這隻適用於nx.get_edge_attributes()和nx.draw_networkx_edge_labels()),如果一個w應該使用nx.get_node_attributes()nx.draw_networkx_labels(),原始節點名稱將被屬性值替換。

我想知道是否有其他方法來標記字典格式屬性在每個節點以外的字典格式,同時保持節點名稱內的節點?我應該如何修改我當前的代碼?

回答

1

不包括鍵的nx.draw_networkx_labels()的問題可以通過創建一個新的字典來解決,該字典會將表示整個字典的字符串保存爲值。

node_attrs = nx.get_node_attributes(G, 'type') 
custom_node_attrs = {} 
for node, attr in node_attrs.items(): 
    custom_node_attrs[node] = "{'type': '" + attr + "'}" 

關於繪圖節點的名稱和屬性,則可以使用nx.draw()正常繪製節點名稱,然後nx.draw_networkx_labels()繪製屬性 - 這裏可以手動換擋屬性位置高於或低於節點。在pos下面的塊中保存節點位置,並且pos_attrs保存放置在適當節點上方的屬性位置。

pos_nodes = nx.spring_layout(G) 
pos_attrs = {} 
for node, coords in pos_nodes.items(): 
    pos_attrs[node] = (coords[0], coords[1] + 0.08) 

完整的示例:

import networkx as nx 
import matplotlib.pyplot as plt 

G = nx.Graph() 
G.add_nodes_from(['a', 'b', 'c', 'd', 'e', 'f', 'g'], type = 'machine') 
G.add_nodes_from(['h', 'i', 'j'], type = 'human') 
G.add_edges_from([('a', 'c'), ('a', 'b'), ('a', 'd'), ('a', 'f'), ('b', 'd'), ('b', 'e'), ('b', 'g'), ('c', 'f'), ('c', 'd'), ('d', 'f'), ('d', 'e'), ('d', 'g'), ('e', 'g'), ('f', 'g'), ('f', 'h'), ('g', 'h'), ('h', 'i'), ('i', 'j')]) 

plt.figure() 
pos_nodes = nx.spring_layout(G) 
nx.draw(G, pos_nodes, with_labels=True) 

pos_attrs = {} 
for node, coords in pos_nodes.items(): 
    pos_attrs[node] = (coords[0], coords[1] + 0.08) 

node_attrs = nx.get_node_attributes(G, 'type') 
custom_node_attrs = {} 
for node, attr in node_attrs.items(): 
    custom_node_attrs[node] = "{'type': '" + attr + "'}" 

nx.draw_networkx_labels(G, pos_attrs, labels=custom_node_attrs) 
plt.show() 

輸出:

enter image description here

最後提示:如果你有很多的邊緣和您的節點屬性難以閱讀,你可以嘗試將邊緣的顏色設置爲較淺的灰色陰影。

+1

非常感謝您澄清這一點,您的答案有助於解決我的問題! –