gpt4 book ai didi

javascript - 在 d3.js 中导入 json 文件

转载 作者:搜寻专家 更新时间:2023-10-31 22:25:58 24 4
gpt4 key购买 nike

我是 d3.js 的新手,我正在从 d3.js 中的 json 数据创建折线图。当 json 数据位于 html 文件中时,代码运行良好,但我想从 html 中提取数据并将数据作为 json 文件引用。示例 index.html 如下所示:

<!DOCTYPE html>
<html lang="en">

<body>
<svg id="visualisation" width="1000" height="500"></svg>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
function InitChart() {
var data = [{
"sale": "202",
"year": "2000"
}, {
"sale": "215",
"year": "2002"
}, {
"sale": "179",
"year": "2004"
}, {
"sale": "199",
"year": "2006"
}, {
"sale": "134",
"year": "2008"
}, {
"sale": "176",
"year": "2010"
}];


var vis = d3.select("#visualisation"),
WIDTH = 1000,
HEIGHT = 500,
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 50
},
xScale = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([2000, 2010]),
yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([134, 215]),
xAxis = d3.svg.axis()
.scale(xScale),
yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");

vis.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
.call(xAxis);
vis.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
var lineGen = d3.svg.line()
.x(function(d) {
return xScale(d.year);
})
.y(function(d) {
return yScale(d.sale);
})
.interpolate("basis");
vis.append('svg:path')
.attr('d', lineGen(data))
.attr('stroke', 'green')
.attr('stroke-width', 2)
.attr('fill', 'none');
}
InitChart();
</script>
</body>

</html>

我想提取 json 数据并在 index.html 中引用它,因为实际的 json 数据以 MB 为单位。因此,我保存了数据并将其在 InitChart() 函数中引用为

var data = d3.json("linedata.json");

html 和 json 文件都在同一个目录中。当我在浏览器 (firefox) 中打开 index.html 时,我得到一个空白页面。可能是什么错误?

最佳答案

问题:

在变量中使用 d3.jsond3.json 不返回任何东西(实际上,它返回一个与请求关联的对象,与文件内容本身无关)。

解决方案:

改用 d3.json(url[, callback])

说明:

D3 提供了一种加载 JSON 文件的方法。你必须这样做:

d3.json("linedata.json", function(data){
function initChart(){
//all your code for initChart here
};
initChart();
});

这样,JSON 文件中的数据与参数 data 相关联,并且可以在回调函数中使用。

这是文档: https://github.com/mbostock/d3/wiki/Requests#d3_json

关于javascript - 在 d3.js 中导入 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36818831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com