我最近开始研究 D3.js 并遇到了一些问题.. 到目前为止,这是我尝试过的:
这是我的 JS:
d3.json("../js/sample2.json", function(data) {
var canvas = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 500)
.attr("border", "black")
var group = canvas.append("g")
.attr("transform", "translate(100,10)")
var line = d3.svg.line()
.x(function(d, i) {
return data[0].position[i];
})
.y(function(d, i) {
return data[1].position[i];
});
var line1 = d3.svg.line()
.x(function(d, i) {
return data[2].position[i];
})
.y(function(d, i) {
return data[3].position[i];
});
var j = 0;
group.selectAll("path")
.data(data).enter()
.append("path")
// Have to provide where exaclty the line array is ! (line(array))
.attr("d", line(data[j].position))
.attr("fill", "none")
.attr("stroke", "green")
.attr("stroke-width", 3);
var group2 = group.append("g")
.attr("transform", "translate(100,10)")
group2.selectAll("path")
.data(data).enter()
.append("path")
// Have to provide where exaclty the line array is ! (line(array))
.attr("d", line1(data[j].position))
.attr("fill", "none")
.attr("stroke", "red")
.attr("stroke-width", 3);
});
这是我的 JSON 文件:
[ {"name": "x1",
"position":[40,60,80,100,200]
},
{"name": "y1",
"position":[70,190,220,160,240]},
{"name": "x2",
"position":[40,60,80,100,200]
},
{"name": "y2",
"position":[20,90,20,60,40]}
]
我希望根据从 JSON 文件中检索到的数据显示该行。 我实际上得到了输出, 这是我当前收到的输出:
但问题是,我希望它更加动态。 例如,如果 JSON 中有更多数据。
JSON 可以来自 x1,y1 to xn,yn...(类似上面JSON中的格式)
[ {"name": "x1",
"position":[40,60,80,100,200]
},
{"name": "y1",
"position":[70,190,220,160,240]
},
{"name": "x2",
"position":[40,60,80,100,200]
},
{"name": "y2",
"position":[20,90,20,60,40]}
.
.
.
.
{"name": "xn",
"position":[40,60,80,100,200]
},
{"name": "yn",
"position":[20,90,20,60,40]}]
所以我的问题是:
- 如何使其动态(即:无论 JSON 中的数据量如何,它都应反射(reflect)在具有所需图表的图表上)
- 使用D3.json 输入到D3js 的JSON 数据格式 会不会有问题? (或者 D3.json 要求的格式到底是什么,是否严格?)
最佳答案
让你的json数据结构变成这样
[
[
{
"x":40,
"y":70
},
{
"x":60,
"y":190
},
{
"x":80,
"y":220
},
{
"x":100,
"y":160
},
{
"x":200,
"y":240
}
],
[
{
"x":40,
"y":20
},
{
"x":60,
"y":90
},
{
"x":80,
"y":20
},
{
"x":100,
"y":60
},
{
"x":200,
"y":40
}
]
]
代码
d3.json("data.json", function(data) {
var canvas = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 500)
.attr("border", "black")
var group = canvas.append("g")
.attr("transform", "translate(100,10)")
var line = d3.svg.line()
.x(function(d, i) {
return d.x;
})
.y(function(d, i) {
return d.y;
});
group.selectAll("path")
.data(data).enter()
.append("path")
.attr("d", function(d){ return line(d) })
.attr("fill", "none")
.attr("stroke", "green")
.attr("stroke-width", 3);
});
这是创建多折线图的正确方法。无论您从 json 中获得什么数据格式,您都可以使用 Javascript 数组函数将其转换为所需的格式。您也可以使用 Underscore.js 来轻松处理。
关于javascript - D3js - 使用 d3.json 从 "JSON data"输入获取绘制的折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22316866/