I am using d3 to create a simple force graph where the data is loaded from a json file graph.json:
{
"nodes": [
{
"user": "John Smith",
"id": 0,
"influence": 30,
"keywords":[["hello", 190], ["regards", 189], ["writing", 139], ["computer", 134], ["this", 133], ["thanks", 131]]
},
{
"user": "Mary Brown",
"id": 1,
"influence": 15,
"keywords":[["plane", 190], ["car", 13], ["truck", 13], ["bike", 13], ["motor", 190], ["engine", 12], ["regards", 12]]
},
{
"user": "Joe Young",
"id": 2,
"influence": 50
}
],
"links": [
{
"id": 0,
"source": 0,
"target": 1,
"weight": 5,
"keywords":[["facebook", 18], ["twitter", 190], ["youtube", 18], ["instagram", 18], ["snapchat", 190], ["whatsapp", 17], ["vibe", 17]]
},
{
"id": 1,
"source": 1,
"target": 2,
"weight": 50
},
{
"id": 2,
"source": 2,
"target": 0,
"weight": 21
}
]
}
However, I want to show only the nodes where their influence is greater or equal to 30. I tried using this if statement inside the .data() function, but it does not work:
var node = svg.selectAll(".node")
.data(json.nodes, function(d){
if (d.influence >= 30)
return d;
})
What am I doing wrong?
Here is the full code:
d3.json("graph.json", function(json) {
force
.nodes(json.nodes)
.links(json.links)
.start();
var link = svg.selectAll(".link")
.data(json.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.weight); })
var node = svg.selectAll(".node")
.data(json.nodes, function(d){
if (d.influence >= 30)
return d;
})
.enter()
.append("g")
.attr("class", "node")
.attr("pointer-events", "none")
.call(force.drag)
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.attr("font-size", function(d){ return d.influence*1.5>9? d.influence*1.5: 9; })//text size
.text(function(d) { return d.user });
node.append("circle")
.attr("r",function(d){ return d.influence/2 ? d.influence :5 ; })// node size
.attr("fill", function(d){ return c10(d.id); }); //colour
force.on("tick", function(d) {
node.attr("r", function(d){ return d.influence; })
.attr("cx", function(d){ return d.x; })
.attr("cy", function(d){ return d.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
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; });
});
force.start();
});
Aucun commentaire:
Enregistrer un commentaire