I am having trouble with dynamically adding nodes on to a d3.js force directed graph and I was wondering if anyone here could shed some light on the subject.
The problem I am having is that I want the tick function to transform all nodes on the graph and not just the newly added ones.
Below are the functions I use for adding nodes and handling the transformation:
// Function to handle tick event
function tick() {
tick_path.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" +
d.source.x + "," +
d.source.y + "L" +
d.target.x + "," +
d.target.y;
});
tick_node.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"; });
}
/**
* Append nodes to graph.
*/
function addNodes2Graph(){
// define the nodes
// selection will return none in the first insert
// enter() removes duplicates (assigning nodes = nodes.enter() returns only the non-duplicates)
var nodes = viz.selectAll(".node")
.data(g_nodes)
.enter().append("g")
.on("click", nodeClick)
.call(force.drag);
// From here on, only non-duplicates are left
nodes
.append("circle")
.attr("r", 12)
.attr("class", "node");
nodes.append("svg:image")
.attr("class", "circle")
.attr("xlink:href", "img/computer.svg")
.attr("x", "-8px")
.attr("y", "-8px")
.attr("width", "16px")
.attr("height", "16px");
// add the text
nodes.append("text")
.attr("x", 12)
.attr("dy", ".35em")
.text(function(d) { return d.ip; });
return nodes;
}
// Execution (snippet)
// Add new nodes
tick_node = addNodes2Graph();
// Add new paths
tick_path = addPaths2Graph();
// Restart graph
force
.nodes(g_nodes) // g_nodes is an array which stores unique nodes
.links(g_edges) // g_edges stores unique edges
.size([width, height])
.gravity(0.05)
.charge(-700)
.friction(0.3)
.linkDistance(150)
.on("tick", tick)
.start();
I think the problem is that I only get non-duplicated results returned from addNodes2Graph which I then use in the tick function but I'm not sure how I could achieve this without adding duplicated nodes on to the graph.
At the moment, it's either adding duplicated elements on to the graph or transform only the new nodes on tick.
Thank you very much for your help in advance.
It looks like you're adding nodes only to the DOM, not to the force layout. To recap, here's what you need to do to add nodes to the force layout.
Add elements to the array that the force layout uses for its nodes. This needs to be the same array that you passed in initially, i.e. you can't create a new array and pass that it if you want smooth behaviour. Modifying force.nodes() should work fine.
Do the same for the links.
Add the new DOM elements using .data().enter() with the new data.
No change to the tick function should be required as adding the nodes and DOM elements is done elsewhere.
After adding the new nodes/links, you need to call force.start() again to have it take them into account.
Related
I'm using d3.js
Hi, I'm having an issue finding how to append two elements (path and image) to the same g (inside my svg) from the same data. I know how to do this, but the tricky thing is I need to get the BBox values of the "path" elements in order to place the "image" elements in the middle... My goal is actually to place little clouds in the center of cities on a map like this : this is the map I am trying to reproduce
On the map it's not centered but I have to do so. So this is my current code:
// Draw the map
svg.append("g")
.selectAll("path")
.data(mapEPCI.features)
.enter()
.append("path")
.attr("fill", d => d.properties.color)
.attr("d", d3.geoPath().projection(projection))
.style("stroke", "white")
.append("image")
.attr("xlink:href", function(d) {
if (d.properties.plan_air == 1)
return ("data/page8_territoires/cloud.png")
else if (d.properties.plan_air == 2)
return ("data/page8_territoires/cloudgray.png")
})
.attr("width", "20")
.attr("height", "15")
.attr("x", function (d) {
let bbox = d3.select(this.parentNode).node().getBBox();
return bbox.x + 30})
.attr("y", function (d) {
return d3.select(this.parentNode).node().getBBox().y + 30})
This gets the right coordinates for my images but it's because the parent node is actually the path... If I append the image to the g element, is there a way to get the "BrotherNode", or maybe the last child of the "g" element ? I don't know if I'm clear enough but I hope you get my point.
I'm kinda new to js so maybe I'm missing something simple I just don't know yet
Thanks for your help
I would handle your data at the g level and create a group for every map feature (country) which contains the path and a sibling image:
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<svg width="600" height="600"></svg>
<script>
let svg = d3.select('svg'),
mapEPCI = {
features: [100, 200, 300, 400]
};
let g = svg.selectAll('g')
.data(mapEPCI.features)
// enter selection is collection of g
let ge = g.enter().append("g");
// append a path to each g according to data
ge.append('path')
.attr("d", (d) => "M" + d + ",10L" + d + ",100")
.style("stroke", "black");
// append a sibling image
ge.append("image")
.attr("xlink:href", "https://placeimg.com/20/15/animals")
.attr("width", "20")
.attr("height", "15")
.attr("transform", function(d) {
// find my sibling path to get bbox
let sibling = this.parentNode.firstChild;
let bbox = sibling.getBBox();
return "translate(" + (bbox.x - 20 / 2) + "," + (bbox.y + bbox.height / 2 - 15 / 2) + ")"
});
</script>
</body>
</html>
Using d3's pack layout, I made some bubbles associated with states. Current test script: https://jsfiddle.net/80wjyxp4/4/. They're colored according to region. You'll note Texas is in the "NW", California in the "SE", etc.
Question:
How would you geographically sort the circles in pack-layout?
One hack way might use the default d3.layout.pack.sort(null). This sort starts with the first data point (in this case, AK) and then adds bubbles in a counterclockwise direction. I could hand-sort data to be input in an order that approximates state positions, and add in blank circles to move edge circles around.
I'm interested about better ideas. Would it be better to use a modified force layout, like http://bl.ocks.org/mbostock/1073373? The d3.geom.voronoi() seems useful.
On this http://bl.ocks.org/mbostock/1073373 look at these lines:
states.features.forEach(function(d, i) {
if (d.id === 2 || d.id === 15 || d.id === 72) return; // lower 48
var centroid = path.centroid(d); // <===== polygon center
if (centroid.some(isNaN)) return;
centroid.x = centroid[0]; <==== polygon lat
centroid.y = centroid[1]; <==== polygon lng
centroid.feature = d;
nodes.push(centroid); <== made node array of centroids
});
----------------
force
.gravity(0)
.nodes(nodes) <==== asign array nodes to nodes
.links(links)
.linkDistance(function(d) { return d.distance; })
.start();
Each state acts like a multi-foci layout. Like this one: http://bl.ocks.org/mbostock/1021841
Started with pack layout, to get circle radii
used state centroids from this modified force layout http://bl.ocks.org/mbostock/1073373
Contrived to avoid overlaps using collisions https://bl.ocks.org/mbostock/7881887
The code is here: https://jsfiddle.net/xyn85de1/. It does NOT run because I can't get data for the topojson file, at http://bl.ocks.org/mbostock/raw/4090846/us.json, from the link, and the file is too large to copy-paste. Download to your own server then run.
It has a hover-title text and transitions in, but ends up looking like this:
Spacing and stuff is modifiable with different parameters. The circles are approximately sorted geographically. MO is that big gold one in the middle; AK and HI are dark blue to the left; CA is lower left in pink; TX is at the bottom in light blue. And so on.
Code:
After collecting all data (location data for init position of circles), along with the state name, value, area (for color coding) into the nodes variable:
// circles
var circles = svg.selectAll("g") //g
.data(nodes)
.enter()
.append("g")
.attr("transform", function(d) {
return "translate(" + -d.x + "," + -d.y + ")";
})
.append("circle")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
.attr("r", function(d) {return d.r;})
.attr("fill", function(d) { return color(d.area); })
.call(force.drag); // lets you change the orientation
// title text
circles.append("title")
.text(function(d) { return d.state + ": " + format(d.value) + " GWh"; });
// // text // doesn't work :/ porque?
// circles.append("text")
// .attr("dy", ".3em")
// //.style("text-anchor", "middle")
// .text(function(d) { return d.state.substring(0, d.r / 3); });
// circle tick function
function tick(e) {
circles
.each(collide(collision_alpha))
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
// force
force.nodes(nodes)
.on("tick", tick)
.start();
I am trying to use the bubble chart example as a template to build a visualisation. I have my JSON as a flat-hierarchy, such that there is one element called children and that holds an array of objects that I want to visualise.
The JSON looks like this:
{
"children":[
{
"acc":"Q15019",
"uid":"SEPT2_HUMAN",
"sym":"SEPT2",
"name":"Septin-2",
"alt_ids":"",
"ratio":0.5494271087884398,
"pval":0.990804718
},
...,
{
"acc":"Q16181",
"uid":"SEPT7_HUMAN",
"sym":"SEPT7",
"name":"Septin-7",
"alt_ids":"",
"ratio":1.1949912048567823,
"pval":0.511011887
}
]
}
I have modified the example code as follows:
var diameter = 960,
format = d3.format(",d"),
color = d3.scale.quantile().range(colorbrewer.RdBu[9]);
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(1.5);
var svg = d3.select("body").append("svg")
.attr("width", diameter)
.attr("height", diameter)
.attr("class", "bubble");
d3.json("datagraph.json", function(datagraph) {
var node = svg.selectAll(".node")
.data(bubble.nodes(datagraph))
.enter().append("g")
.attr("class", "node")
.attr("id", function(d) { return d.acc; })
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
//node.append("title").text(function(d) { return d.className + ": " + format(d.value); });
node.append("circle")
.attr("r", function(d) { return 30; })
.style("fill", function(d) {
if(d.ratio == null)
return "#ffffff";
else
return color(d.ratio);
});
node.append("text")
.attr("dy", ".3em")
.style("text-anchor", "middle")
.text(function(d) { return d.acc; });
});
The resultant HTML has a ton of <g> tags responding to each element except they are never translated to the right position, but instead sort of sit on top of each other on the top left corner. By investigating in Firebug, I figured this happens presumably because the pack() algorithm does not get the objects one at a time, but the whole array as a single element, thus individual elements don't get .x and .y values.
If I change the .nodes() argument to datagraph.children I get the elements one at a time in nodes() iteration, but oddly enough I get a single <g> object. Since I don't need to flatten a hierarchy I skipped the classes(root) function, in the example. What I am wondering is whether or not the packageName attribute plays any role in the nodes()?
How can I resolve this issue?
You haven't specified a value accessor:
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(1.5)
.value(function(d) { return d.pval; }) //<- must return a number
Example here.
How do I apply d3.behavior.drag() to the following arc?
var arc = d3.svg.arc()
.innerRadius(50)
.outerRadius(70)
.startAngle(45 * (pi/180)) //converting from degs to radians
.endAngle(3) //just radians
vis.append("path")
.attr("d", arc)
.attr("transform", "translate(200,200)")
I want to be able to drag the arc around. I have not been able to see anything that uses the drag behavior on any SVG path based object (only for basic elements like circle, rectangle, etc.)
The closest thing I can find related to dragging is this:
http://bl.ocks.org/mbostock/1557377
Though it appears that if you try to ".on("drag", dragmove) for the appended path (.append("path")) "d" comes out as undefined. And if you attach ".on("drag", dragmove)" to the arc itself, the event doesn't appear to fire...)
Drag is a behaviour that you create and then apply to the elements you want to execute that behaviour. There should be no issue applying it to an arc.
So with your arc (minor modification to make the translation accessible):
var position = [200,200];
var arc = vis.append("path")
.attr("d", arc)
.attr("transform", "translate(" + position + ")");
Start by creating the behavior you want. Our drag will update the translation of the arc:
var drag = d3.behavior.drag()
.on("drag", function(d,i) {
position[0] += d3.event.dx;
position[1] += d3.event.dy;
d3.select(this)
.attr("transform", function(d,i){
return "translate(" + position + ")"
})
});
Now we attach the behaviour to the arc:
arc.call(drag);
You can try it yourself here.
I have a force directed graph with different size nodes. I want to display a custom icon in the middle of each path connecting two nodes. From the d3 examples I found the way to display images within the nodes. However, when I try the same technique on the paths, the images are not shown.
var path = svg.append("svg:g").selectAll("path").data(force.links());
var pathEnter = path.enter().append("svg:path");
pathEnter.attr("class", function(d) {
return "link " + d.target.type;
})
pathEnter.append("svg:g").append("image")
.attr("xlink:href","http://127.0.0.1:8000/static/styles/images/add.png")
.attr("x",0).attr("y",0).attr("width",12).attr("height", 12)
.attr("class", "type-icon");
I guess I need a bit more patience before asking a question. The way I solved the problem is:
var icon = svg.append("svg:g").selectAll("g")
.data(force.links()).enter().append("svg:g");
icon.append("image").attr("xlink:href","imagePath")
.attr("x", -20)
.attr("y", -2)
.attr("width", 12).attr("height", 12)
.attr("class", "type-icon");
And then in the tick function:
icon.attr("transform", function(d) {
return "translate(" +((d.target.x+d.source.x)/2) + "," +
((d.target.y+d.source.y))/2 + ")";
});
to get the center point between the two nodes.