如何使用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
相关产品推荐
相关产品推荐

