最近我开始学习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 到 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中有多少数据,它都应反映在图表中并显示所需的图形)
- JSON的数据格式是否会对使用D3.json的D3js造成问题? (或者D3.json所需的确切格式是什么,它是否严格?)