Pyvis 网络不断前进

问题描述 投票:0回答:3

我有一个文本语料库,我想将其中的单词共现可视化为网络。 为此,我创建了一个 pd 数据框

cooc_pd
,其中包含列
Source
Target
Weight
。前两个是节点,
Weight
表示这两个节点(单词)在一组 window_size 内出现的频率。

然后,我使用以下代码来绘制网络:

import networkx as nx
from pyvis.network import Network
import pandas as pd

G = nx.from_pandas_edgelist(cooc_pd, 
                            source = 'Source', 
                            target = 'Target',
                            edge_attr='Weight')

net = Network(notebook=True)
net.from_nx(G)
net.show("example.html")
 

如果我选择较低的权重包含阈值,则图中会显示许多连接。然而,在这种情况下,

example.html
中的节点不断移动,解释起来很困难。有没有办法(除了增加阈值)使节点停止移动?

python-3.x pandas graph networkx pyvis
3个回答
11
投票

我的图表也遇到同样的问题,它一直以嘈杂的方式移动。

阅读文档,我发现了一种名为repulsion的方法,该方法“将整个网络的物理属性设置为斥力”。

创建网络后,我插入了它并且运行良好:

from pyvis.network import Network

net = Network()
net.repulsion()

2
投票

你可以使用

net.show_buttons(filter_=['physics']) 

使用可视化中的滑块管理物理参数。

在 PyVis 文档中阅读更多内容这里


0
投票

问题在于

toggle_physics(False)
不允许生成的 html 使用基于物理的算法(例如基于 Force Atlas 2 的算法)对节点进行初始分组。所以我们真正想做的是在
G.show_buttons(filter_=['physics']) 
之后禁用物理并立即关闭物理,但更强大的解决方案是编辑 html 本身,以便在所有内容加载后自动关闭物理。这可以通过调用以下函数来完成:

import re

def add_physics_stop_to_html(filepath):
    with open(filepath, 'r', encoding="utf-8") as file:
        content = file.read()

    # Search for the stabilizationIterationsDone event and insert the network.setOptions line
    pattern = r'(network.once\("stabilizationIterationsDone", function\(\) {)'
    replacement = r'\1\n\t\t\t\t\t\t  // Disable the physics after stabilization is done.\n\t\t\t\t\t\t  network.setOptions({ physics: false });'

    new_content = re.sub(pattern, replacement, content, flags=re.DOTALL)

    # Write the modified content back to the file
    with open(filepath, 'w', encoding="utf-8") as file:
        file.write(new_content)

# Example usage
nt.write_html('nx.html')
add_physics_stop_to_html("nx.html")

© www.soinside.com 2019 - 2024. All rights reserved.