【问题标题】:(Python) Networkx - Define own pos dictionary(Python) Networkx - 定义自己的 pos 字典
【发布时间】:2019-03-29 23:08:23
【问题描述】:

我的代码是这样的:

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()

我的 print 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 个节点中的每一个设置我自己的位置?

提前谢谢你, 问候:)

【问题讨论】:

    标签: python dictionary layout networkx pos


    【解决方案1】:

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

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

    即使您为该节点定义了位置,它仍然无法绘制,因为该节点不在图表中。

    【讨论】:

    • 好的,我明白了,但是我如何修复它以在数据前面仍然有标签?我可以使用 for 循环将标签添加到 flattened_list_nodes 吗?或者什么是最好的解决方案?那么我如何为节点设置我自己的 pos 字典呢?
    • 不要在节点名称中添加额外的文本,而是查看stackoverflow.com/a/28533293/2966723 的最后一部分。如果您真的想在节点名称中添加文本,则需要更新节点列表以包含该额外文本。否则,在您要求它绘制'16.37.97.17' 的绘图命令中,它无法知道它真的应该绘制'sIP:\n16.37.97.17'。但是您最好的选择是更新节点标签,而不是更新我链接到的答案中的节点名称。
    猜你喜欢
    • 2023-03-07
    • 2012-08-15
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2012-01-21
    • 2020-07-02
    相关资源
    最近更新 更多