此代码与下面给出的JSON data1对象一起工作正常但我希望此代码可以使用此new_json对象。我想要在节点上建立链接id.Any help?
CachedServiceClient
答案 0 :(得分:1)
基本上,强制布局与索引相关,而不是id或名称。所以你必须具体说你想在你的情况下通过id链接:
var edges = [];
data.links.forEach(function(e) {
var sourceNode = data.nodes.filter(function(n) {
return n.id === e.source;
})[0],
targetNode = data.nodes.filter(function(n) {
return n.id === e.target;
})[0];
edges.push({
source: sourceNode,
target: targetNode
});
});
上面的代码检查哪个节点具有与链接Source相同的id,然后将其推送到edges数组的源中,并将其推送到目标。然后使用此edge数组创建图形:
力量:
force
.nodes(data.nodes)
.links(edges)
对于链接:
var link = svg.selectAll(".link")
.data(edges)
以下是我使用new_json
:https://jsfiddle.net/thatOneGuy/60oLwg8t/1/
或者在这里:
var data =
{
"nodes": [{
"id": 124587,
"name": "paper1",
"citation": 5,
"group": 1
}, {
"id": 178456,
"name": "paper2",
"citation": 8,
"group": 2
}],
"links": [{
"source": 124587,
"target": 178456,
"name": "A-B-1",
"value": 8
}]
};
console.log(data.nodes)
console.log(data.links)
var width = 960,
height = 500;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var edges = [];
data.links.forEach(function(e) {
var sourceNode = data.nodes.filter(function(n) {
return n.id === e.source;
})[0],
targetNode = data.nodes.filter(function(n) {
return n.id === e.target;
})[0];
edges.push({
source: sourceNode,
target: targetNode,
value: e.Value
});
});
force
.nodes(data.nodes)
.links(edges)
.start();
var link = svg.selectAll(".link")
.data(edges)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", 2);
var node = svg.selectAll(".node")
.data(data.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", 'red')
.call(force.drag);
node.append("title")
.text(function(d) {
return d.name;
});
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("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
});
});

.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #999;
stroke-opacity: .6;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;