You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML中展示支持节点拖拽的可交互NetworkX关系图

实现方案

方案1:使用Pyvis库(推荐,最贴合需求)

Pyvis专门用于生成可交互的网络关系图,原生支持对接NetworkX的图对象,导出的HTML自带节点拖拽、缩放、悬停高亮等效果,也可以通过布局参数避免节点重叠。

  • 安装依赖
pip install pyvis
  • 适配现有代码的示例:
import networkx as nx
from pyvis.network import Network

# 原有图构建逻辑保持不变
G = nx.Graph()
G.add_nodes_from(nodes) # nodes为原有的节点列表
G.add_edges_from(edges) # edges为原有的边列表

# 初始化Pyvis网络实例
# cdn_resources='inline'表示所有依赖资源打包进HTML,无需联网即可使用
net = Network(height="800px", width="100%", notebook=False, cdn_resources='inline')

# 导入NetworkX构建的图
net.from_nx(G)

# 配置物理引擎参数,避免节点重叠,拖拽节点后会自动调整布局
net.barnes_hut(
    gravity=-8000, # 负值代表节点互斥,数值越大排斥力越强,越不容易出现重叠
    central_gravity=0.3,
    spring_length=200, # 边的默认长度,调大可拉开节点间距
    spring_strength=0.05
)

# 显式开启交互配置
net.set_options("""
{
  "interaction": {
    "dragNodes": true,
    "zoomView": true,
    "dragView": true
  }
}
""")

# 直接导出为HTML文件,浏览器打开即可使用
net.save_graph("network_graph.html")
  • 效果说明:生成的network_graph.html支持鼠标自由拖拽任意节点调整位置、滚动缩放画布、拖拽画布移动视角,悬停在节点上会显示节点名称,也可根据需求自定义节点颜色、大小、边的样式等属性。

方案2:使用Plotly生成交互关系图(适合需要和其他Plotly图表联动的场景)

如果项目已使用Plotly做可视化,也可以将NetworkX的布局数据导出后用Plotly绘制,生成HTML文件。

  • 安装依赖
pip install plotly
  • 适配现有代码的示例:
import networkx as nx
import plotly.graph_objects as go

# 原有图构建逻辑保持不变
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
# 调大k值可以增大节点间距,避免重叠
pos = nx.spring_layout(G, scale=2, k=0.5)

# 提取边的坐标
edge_x = []
edge_y = []
for edge in G.edges():
    x0, y0 = pos[edge[0]]
    x1, y1 = pos[edge[1]]
    edge_x.extend([x0, x1, None])
    edge_y.extend([y0, y1, None])

edge_trace = go.Scatter(
    x=edge_x, y=edge_y,
    line=dict(width=0.5, color='#888'),
    hoverinfo='none',
    mode='lines')

# 提取节点的坐标和文本
node_x = []
node_y = []
node_text = []
for node in G.nodes():
    x, y = pos[node]
    node_x.append(x)
    node_y.append(y)
    node_text.append(str(node))

node_trace = go.Scatter(
    x=node_x, y=node_y,
    mode='markers+text',
    text=node_text,
    textposition="top center",
    hoverinfo='text',
    marker=dict(
        showscale=True,
        size=10,
        colorbar=dict(
            thickness=15,
            title='节点度数',
            xanchor='left',
            titleside='right'
        )
    )
)

# 配置节点颜色为对应节点度数
node_adjacencies = []
for node, adjacencies in enumerate(G.adjacency()):
    node_adjacencies.append(len(adjacencies[1]))
node_trace.marker.color = node_adjacencies

# 生成画布
fig = go.Figure(data=[edge_trace, node_trace],
             layout=go.Layout(
                showlegend=False,
                hovermode='closest',
                margin=dict(b=0,l=0,r=0,t=0),
                xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
                yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))
                )

# 导出为HTML文件
fig.write_html("plotly_network.html")

注意:Plotly生成的关系图默认不支持自由拖拽节点调整位置,仅支持画布缩放、拖拽移动视角,如果需要节点拖拽功能优先选择Pyvis方案。

内容的提问来源于stack exchange,提问作者Almog G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:24:02