python - NetworkX - 阻止节点聚集 - 尝试 Scale/K 参数

标签 python matplotlib networkx

我有大约 28 个节点,其中大多数节点之间都有边,有些是孤立的(没有边)。孤立的节点分布得很好,但连接的节点却堆积得很厉害,我看不到任何东西。我尝试了各种 node_sizes、scale 和 k 参数,它总是给我(大致)相同的结果。有什么办法可以强制看到更好的景色吗?

nx.draw_spring(candidateGraph, node_size = 1000, with_labels=True, scale=100, weight=weightVal, k=100)

plt.show( )

enter image description here

最佳答案

有多种方法可以做到这一点。

首先评论一下networkx如何绘制东西。这是documentation 。它创建一个字典 pos ,其中包含每个节点的坐标。使用draw_networkx,您可以向其发送可选参数pos=my_position_dict

Networkx 还具有可以为您定义位置的命令。这样您就可以更好地控制事情。

您有多种选择来完成您想做的事情。

最简单的方法是仅绘制连接的组件并省略孤立的节点。

nodes_of_largest_component  = max(nx.connected_components(G), key = len)
largest_component = G.subgraph(nodes_of_largest_component)
nx.draw_spring(largest_component)

另一种方法是尝试其他(非 Spring )布局之一。例如:

nx.draw_spectral(G)

或者,您可以开始操纵位置。一种方法是将几个位置设置为固定,然后让 spring_layout 处理其余的位置。

pre_pos = {Huck: (0,0), Christie:(0,1), Graham:(1,1), Bush: (1,2)}
my_pos = nx.spring_layout(G, pos=pre_pos, fixed = pre_pos.keys())
nx.draw_networkx(G,pos=my_pos)

然后它将保存您在fixed中指定的固定节点。

或者,仅定义最大组件的所有位置。然后保持这些固定并添加其他节点。最大的组件将“填充”大部分可用空间,然后我认为 spring_layout 将尝试保持添加的节点不会太远(或者,一旦您看到布局,您可以通过以下方式指定这些节点)手)。

nodes_of_largest_component  = max(nx.connected_components(G), key = len)
largest_component = G.subgraph(nodes_of_largest_component)
pos = nx.spring_layout(largest_component)
pos = nx.spring_layout(G,pos=pos,fixed=nodes_of_largest_component)
nx.draw_networkx(G,pos=pos)

还有一件事需要注意,每次调用 spring_layout 都会导致不同的布局。这是因为它从一些随机位置开始。这就是为什么保存位置字典很有用的部分原因,特别是如果您打算对图形做任何花哨的事情。

关于python - NetworkX - 阻止节点聚集 - 尝试 Scale/K 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33724909/

相关文章:

Python Webbrowser 模块永远不会在新窗口中打开链接

python - 将文件中的不同列附加到不同的列表?

python 3 : matplotlib plotting four lines with dictionary

python - 如何修改networkx中节点的轮廓颜色?

NetworkX - 删除节点并重新连接边缘

python - pandas 数据框,将 index_col 设置为我的 csv 名称

python - 创建 AWS S3 存储桶时,region None 是什么意思?

matplotlib - 将RGB元组转换为实数的关系

python - 如何在python中的无向图中有效地计算三元组人口普查

python - 如何从节点列表中获取对应的边