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

如何使用JSON数据在D3.js中绘制rect矩形并解决无法渲染问题

D3可视化矩形不显示问题修复方案

问题根因

  • 异步请求时序错误:JSON数据请求是异步操作,当前矩形渲染逻辑写在请求回调外,执行渲染时dataSet还未被赋值,没有数据源自然无法生成矩形元素。
  • SVG属性拼写错误:设置SVG高度时错误拼写为heigth,正确属性名为height。
  • 坐标计算逻辑错误:矩形x坐标使用d[1][i]计算完全不成立,d[1]是单条数据的GDP数值(数字类型),不存在[i]下标,计算结果为NaN导致矩形定位异常。

修正后代码

let dataSet;
let data;
function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

const w = 700;
const h = 500;

const svg = d3.select("body")
  .append("svg")
  .attr("width",w)
  .attr("height",h)
  .attr("style", "outline: thin solid red;");

readTextFile("https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json", function(text){
    data = JSON.parse(text);
    dataSet = data["data"]
    svg.selectAll("rect")
      .data(dataSet)
      .enter()
      .append("rect")
      .attr("x", (d,i) => i * 30 + 10)
      // 如需实现y轴翻转,替换上方y属性为下方代码
      // .attr("y", d => h - d[1]/2)
      .attr("y", 0)
      .attr("width", 25)
      .attr("height", d => d[1] / 2 )
      .attr("fill", "navy")
      .attr("class", "bar")
      .append("title")
      .text(d => d)

    svg.selectAll("text")
      .data(dataSet)
      .enter()
      .append("text")
      .text(d => d)
      .attr("x", (d, i) => i * 30 +10)
      .attr("y", 15)
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:48:01