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

为何无法在div中显示D3图表?技术问题咨询

问题排查与修复

核心问题1:DOM元素加载顺序错误

你的JavaScript代码写在<div id="plot-div">之前,浏览器从上到下解析HTML,脚本运行时#plot-div元素还未被创建,d3.select("#plot-div")找不到目标容器,无法将SVG添加进去。

核心问题2:重复引入D3库

同时加载了d3.js和d3.min.js,这两个是同一库的未压缩/压缩版本,重复引入可能引发冲突,只需保留其中一个即可。


修正后的完整代码

<!DOCTYPE html>
<html>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <title>Protein Structure Analyzer</title>
      <script type="text/javascript" src="../static/jquery/jquery-3.6.3.js"></script>
      <!-- 仅保留一个D3库文件 -->
      <script type="text/javascript" src="../static/d3/d3.min.js"></script>
    </head>
    <body>
    <!-- 先渲染目标容器 -->
    <div id="plot-div"></div>
    <!-- 再执行绘图脚本 -->
    <script type="text/javascript">
    // 设置图表尺寸与边距
    var margin = {top: 10, right: 40, bottom: 30, left: 30},
        width = 450 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;

    // 将SVG添加到目标div中
    var svG = d3.select("#plot-div")
      .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform",
              "translate(" + margin.left + "," + margin.top + ")");

    // 定义数据
    var data = [ {x:10, y:20}, {x:40, y:90}, {x:80, y:50} ]

    // X轴比例尺与轴绘制
    var x = d3.scaleLinear()
        .domain([0, 100])         
        .range([0, width]);       
    svG
      .append('g')
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));

    // Y轴比例尺与轴绘制
    var y = d3.scaleLinear()
        .domain([0, 100])         
        .range([height, 0]);       
    svG
      .append('g')
      .call(d3.axisLeft(y));

    // 添加数据点
    svG
      .selectAll("whatever")
      .data(data)
      .enter()
      .append("circle")
        .attr("cx", function(d){ return x(d.x) })
        .attr("cy", function(d){ return y(d.y) })
        .attr("r", 7)
    </script>
    </body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:02:57