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

在VSCode的Jupyter Notebook中用D3.js绘制交互式网络图失败求助

问题分析与解决方案

核心问题

你的代码存在三个关键问题导致网络图无法显示:

  1. NetworkX生成的边数据默认缺失value字段,D3中Math.sqrt(d.value)会返回NaN,导致链接样式失效
  2. 未确保DOM元素加载完成就执行D3代码,可能出现元素选择失败
  3. 默认的力导向参数设置可能导致节点过于拥挤,不易观察

修正后的完整代码

1. Python 数据准备部分

import networkx as nx
    
G = nx.Graph()

# 添加边时统一设置value属性,或后续批量补全
G.add_edge(1, 2, value=1)
G.add_edge(1, 3, value=1)
G.add_edge(2, 3, value=1)
G.add_edge(3, 4, value=1)
G.add_edge(4, 5, value=1)

# 若不想逐个添加,可批量补全value字段
# for u, v in G.edges():
#     G.edges[u, v]['value'] = 1

2. HTML与D3渲染部分

from IPython.display import display, HTML
html = """
<div id="graph" style="width: 500px; height: 500px;"></div>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
// 确保DOM加载完成后执行渲染逻辑
document.addEventListener('DOMContentLoaded', function() {
    var data = %s;

    // 兼容无value字段的情况,避免计算错误
    data.links.forEach(function(link) {
        if (!link.value) link.value = 1;
    });

    var svg = d3.select("#graph").append("svg")
        .attr("width", 500)
        .attr("height", 500);

    var simulation = d3.forceSimulation(data.nodes)
        .force("link", d3.forceLink(data.links).id(function(d) { return d.id; }))
        .force("charge", d3.forceManyBody(-120)) // 增大排斥力,避免节点拥挤
        .force("center", d3.forceCenter(250, 250))
        .on("tick", ticked);

    var link = svg.append("g")
        .attr("stroke", "#999")
        .attr("stroke-opacity", 0.6)
        .selectAll("line")
        .data(data.links)
        .join("line")
        .attr("stroke-width", function(d) { return Math.sqrt(d.value) || 1; });

    var node = svg.append("g")
        .attr("stroke", "#fff")
        .attr("stroke-width", 1.5)
        .selectAll("circle")
        .data(data.nodes)
        .join("circle")
        .attr("r", 8) // 增大节点半径,提升可见性
        .attr("fill", "#2196F3");

    node.append("title")
        .text(function(d) { return d.id; });

    function ticked() {
        link
            .attr("x1", function(d) { return d.source.x; })
            .attr("y1", function(d) { return d.source.y; })
            .attr("x2", function(d) { return d.target.x; })
            .attr("y2", function(d) { return d.target.y; });

        node
            .attr("cx", function(d) { return d.x; })
            .attr("cy", function(d) { return d.y; });
    }
});
</script>
""" % nx.node_link_data(G)

3. 执行渲染

display(HTML(html))

导出HTML文件注意事项

当将Jupyter Notebook导出为HTML时,需确保:

  • 在VSCode导出选项中勾选**"Enable interactivity"**
  • 确认导出工具保留内联脚本代码,避免过滤D3相关逻辑

内容的提问来源于stack exchange,提问作者Guilherme Reis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 16:32:50