我想从 JSON 文件中的链接数据获取节点列表。 后来我想绘制一个带有链接和边的图表。
我的示例 json 文件:
{
"links": [
{ "source":0, "target":1, "value":20, "orientation":"down" },
{ "source":1, "target":2, "value":1, "orientation":"left" },
{ "source":2, "target":3, "value":1, "orientation":"right" }
]
}
我的 JS 函数:
$(function() {
var width = 500,
height = 300;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.gravity(.05)
.distance(100)
.charge(-100)
.size([width, height]);
d3.json("test_1.json", function(error, json) {
if (error) throw error;
var count = 0;
var nodes = [];
json.links.forEach(function(e) {
count++;
nodes.push({name: "test_"+e.source, orientation: e.orientation});
});
console.log("Count is : "+count);
force
.nodes(json.nodes)
.links(json.links)
.start();
var link = svg.selectAll(".link")
.data(json.links)
.enter().append("line")
.attr("class", "link");
var node = svg.selectAll(".node")
.data(json.nodes)
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("class", "node")
.attr("r", 5);
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});
});
});
我无法从函数中获取列表,因为 JSON 的 forEach 方法似乎有错误。
有人可以帮忙吗?
更新:添加了完整的代码。
错误: 无法读取未定义的属性“权重”。
所以我在 JSON 中添加了一些节点,因为我认为 d3 总是需要一个节点。
最佳答案
只要将新创建的节点数组分配给nodes
变量,您应该将其传递给您的强制布局,而不是links.nodes
。
force
.nodes(nodes)
.links(json.links)
.start();
或者只是将其添加到links
对象
...
json.links.forEach(function(e) {
count++;
nodes.push({name: "test_"+e.source, orientation: e.orientation});
});
links.nodes = nodes;
...
关于javascript - 在 D3 的情况下,我可以绘制仅包含 json 文件中的链接的图表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33957904/