(Python)Networkx-定义自己的pos词典

时间:2018-10-25 10:53:38

标签: python dictionary layout networkx pos

我的代码是这样的:

for x in xrange(5):
    G.add_edge('sIP:\n'+mostfrequent[x][0], countermfi[x])
    G.add_edge('dIP:\n'+mostfrequent[x][1], countermfi[x])
    G.add_edge('sPort:\n'+mostfrequent[x][2], countermfi[x])
    G.add_edge('dPort:\n'+mostfrequent[x][3], countermfi[x])
    G.add_edge('Protocol:\n'+mostfrequent[x][4], countermfi[x])
    G.add_edge('Packets:\n'+mostfrequent[x][5], countermfi[x])
    G.add_edge('Bytes:\n'+mostfrequent[x][6], countermfi[x])


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

#Hyperedges
nx.draw_networkx_nodes(G, pos, nodelist=countermfi, node_size=node_size, node_color='red', node_shape='s', alpha=1)             

#Nodes          
nx.draw_networkx_nodes(G, pos, nodelist=flattened_list_nodes, node_size=1600, node_color='blue', alpha=0.6)             

#Edges
nx.draw_networkx_edges(G, pos, edgelist=G.edges(), width=2)

#Labels
nx.draw_networkx_labels(G, pos, font_size=11, font_family='sans-serif')
plt.axis('off')
plt.show()

我的打印G.nodes(data = True)输出是:

[('Bytes:\n620', {}), ('dIP:\n178.237.19.228', {}), ('sPort:\n2049', {}), ('sPort:\n60179', {}), ('sIP:\n16.37.97.29', {}), (153, {}), ('dPort:\n443', {}), ('dPort:\n80', {}), ('Packets:\n2', {}), ('Packets:\n1', {}), ('sPort:\n44492', {}), ('Bytes:\n100', {}), ('sIP:\n16.37.93.196', {}), ('dIP:\n178.237.17.97', {}), (188, {}), ('dIP:\n16.37.157.74', {}), ('sIP:\n16.37.97.222', {}), ('dIP:\n178.237.17.61', {}), ('sIP:\n16.37.97.17', {}), ('Bytes:\n46', {}), (224, {}), (227, {}), ('dPort:\n691', {}), ('dIP:\n104.131.44.62', {}), ('sPort:\n55177', {}), ('Protocol:\n6', {}), (120, {}), ('sPort:\n56326', {})]

我在使用nx.kamada_kawai_layout时遇到问题,因为出现错误:

raise nx.NetworkXError('Node %s has no position.' % e)
networkx.exception.NetworkXError: Node '16.37.97.17' has no position.

如何解决此问题或为40个节点中的每个节点设置自己的pos?

预先感谢您, 问候:)

1 个答案:

答案 0 :(得分:0)

根据您的other question,您的问题是'16.37.97.17'中出现的节点flattened_list_nodes 不是图中的节点。添加边缘时,将在节点名称后附加一些文本。因此,您添加了节点'sIP:\n16.37.97.17'

然后,您要求networkx绘制节点'16.37.97.17',但这不是图形的一部分,因此,pos没有位置。因此它将失败。您需要在将节点添加到图中之前不更改其名称,或者在nodelist中使用更改后的名称。

即使为该节点定义位置,由于该节点不在图中,它仍将无法绘制。