d3 Exit / Update function in animation - animation

I am trying to do an animation that shows data from ten different points. The graphic is coded so that the sensors (displayed through circles) change their color and size depending on the overall data obtained over one hour (total number of entries and average of speed).
Through this entry (Transition not working d3) and the code from this simulation of Gapminder (https://bost.ocks.org/mike/nations/), I have been able to animate the chart. However, because of the structure of the code, the exit and update function do not work. The first entry in the data at Hour 1 only has one object and therefore only one circle is drawn. This circle gets updated through time, but the other sensors are not drawn (and therefore not updated).
I am considering recreating a first empty object for each sensor to draw them at the beginning of the animation. However, I would like to avoid that.
The code is this:
//FUNCTION TO GET THE DATA BY HOUR
function getDataByHour (hour) {
var allBridges = new Array();
var found;
for (b = 0; b < boatsByHour.length; b++){
bridges.forEach(function(br,i){
if (boatsByHour[b].sensorID== br.id){
xy = projection([br.longitude, br.latitude])}
});
if (boatsByHour[b].hour == hour){
found = true;
bridgeNumber = boatsByHour[b].sensorID;
allBridges.push({
"numberBoats": (boatsByHour[b].numberBoats),
"speed": (boatsByHour[b].speedAvg),
"bridge": boatsByHour[b].sensorID,
"longitude": xy[0],
"latitude": xy[1],
"hour": boatsByHour[b].hour
})
}
}
return allBridges;
}
//SENSORS
var sensor = plot.append("g")
.attr("class","bridges")
.selectAll(".sensors")
.data(getDataByHour(timeRange[0]))
.call(animateSensors)
.enter()
.append("circle")
.attr("class","sensors")
.attr("cx", function(d,i){return d.longitude})
.attr("cy", function(d,i){return d.latitude})
.on("mouseover",function(d){console.log(d)});
sensor.exit().remove();
plot
.transition()
.duration(300000)
.ease(d3.easeLinear)
.tween("hour", tweenHour)
//FUNCTION THAT UPDATES THE ANIMATION
function animateSensors (sensor){
sensor
.attr("r",function(d){return radiusScale(d.numberBoats)})
.style("fill",function(d){return colorScale(d.speed)});
}
function tweenHour(){
var hour = d3.interpolateNumber (timeRange[0],timeRange[1]);
return function(h){
displayHour(hour(h))}
}
function displayHour(hour) {
sensor.data(getDataByHour(Math.floor(hour))).call(animateSensors);
}
I have tried different ways of including the enter() and exit (). If I add the enter() and append the circles inside the 'animateSensors' function, all the circles (sensors) are drawn. However they are not being updated, so at the end, I get thousands of circles drawn in the SVG even if the exit().remove() update is in it.
Thanks

Ok, now it works. Instead of calling the first part of the data (where there is only 1 circle is drawn instead of the total 10), I had to call data that had data for all the circles (like the last point):
var sensor = plot.append("g")
.attr("class","bridges")
.selectAll(".bridge")
.data(getDataByHour(timeRange[1])) // instead of getDataByHour(timeRange[0])
.enter()
.append("circle")
.attr("class",function(d){return "bridge " + d.bridge})
.attr("cx", function(d,i){return d.longitude})
.attr("cy", function(d,i){return d.latitude})
.on("mouseover",function(d){console.log(d)});
The animation starts correctly thanks to the function tweenHour
function tweenHour(){
var hour = d3.interpolateNumber (timeRange[0],timeRange[1]);
return function(h){
displayHour(hour(h))}
}

Related

D3.js binding nested data

I'm really new to coding, and also to asking questions about coding. So let me know if my explanation is overly complex, or if you need more context on anything, etc.
I am creating an interactive map of migration flows on the Mediterranean Sea. The flows show origin and destination regions of the migrant flows, as well as the total number of migrants, for Italy and Greece. Flows should be displayed in a Sankey diagram like manner. Because I am displaying the flows on a map and not in a diagram fashion, I am not using D3’s Sankey plugin, but creating my own paths.
My flow map, as of now (curved flows are on top of each other, should line up next to each other)
For generating my flows I have four points:
2 points for the straight middle part of the flow (country total)
1 point each for the curved outer parts (origin and destination region), using the two points of the straight middle part as starting points
The straight middle and both curved outer parts are each generated independently from their own data source. Flow lines are updated by changing the data source and calling the function again. The flow lines are generated using the SVG path mini-language. In order for the curved outer parts of the flows to show correctly, I need them to be lined up next to each other. To line them up correctly, I need to shift their starting points. The distance of the shift for each path element is determined by the width of the path elements before it. So, grouping by country, each path element i needs to know the sum of the width of the elements 0-i in the same group.
After grouping my data with d3.nest(), which would allow me to iterate over each group, I am not able to bind the data correctly to the path elements
I also can't figure out a loop function that adds up values for all elements 0-i. Any help here? (Sorry if this is kind of unrelated to the issue of binding nested data)
Here is a working function for the curved paths, working for unnested data:
function lineFlow(data, flowSubGroup, flowDir) {
var flowSelect = svg.select(".flowGroup").select(flowSubGroup).selectAll("path");
var flow = flowSelect.data(data);
var flowDirection = flowDir;
flow.enter()
.append("path").append("title");
flow
.attr("stroke", "purple")
.attr("stroke-linecap", "butt")
.attr("fill", "none")
.attr("opacity", 0.75)
.transition()
.duration(transitionDur)
.ease(d3.easeCubic)
.attr("d", function(d) {
var
slope = (d.cy2-d.cy1)/(d.cx2-d.cx1),
dist = (Math.sqrt(Math.pow((d.rx2-d.rx1),2)+Math.pow((d.ry2-d.ry1),2)))*0.5,
ctrlx = d.rx1 + Math.sqrt((Math.pow(dist,2))/(1+Math.pow(slope,2)))*flowDirection,
ctrly = slope*(ctrlx-d.rx1)+d.ry1;
return "M"+d.rx1+","+d.ry1+"Q"+ctrlx+","+ctrly+","+d.rx2+","+d.ry2})
.attr("stroke-width", function(d) {return (d.totalmig)/flowScale});
flowSelect
.select("title")
.text(function(d) {
return d.region + "\n"
+ "Number of migrants: " + addSpaces(d.totalmig)});
};
I tried adapting the code to work with data grouped by country:
function lineFlowNested(data, flowSubGroup, flowDir) {
var g=svg.select(".flowGroup").select(flowSubGroup).append("g").data(data).enter();
var gflowSelect=g.selectAll("path");
var gflow=gflowSelect.data (function(d) {return d.values});
gflow.enter()
.append("path");
gflow.attr("stroke", "purple")
.attr("stroke-linecap", "butt")
.attr("fill", "none")
.attr("opacity", 0.75)
// .transition()
// .duration(transitionDur)
// .ease(d3.easeCubic)
.attr("d", function(d) {
var
slope = (d.cy2-d.cy1)/(d.cx2-d.cx1),
dist = (Math.sqrt(Math.pow((d.rx2-d.rx1),2)+Math.pow((d.ry2-d.ry1),2)))*0.5,
ctrlx = d.rx1 - Math.sqrt((Math.pow(dist,2))/(1+Math.pow(slope,2)))*flowDirection,
ctrly = slope*(ctrlx-d.rx1)+d.ry1;
return "M"+d.rx1+","+d.ry1+"Q"+ctrlx+","+ctrly+","+d.rx2+","+d.ry2})
.attr("stroke-width", function(d) {return (d.totalmig)/flowScale});
};
which isn't working. What am I doing wrong? Thanks for any hints!

Reload nested data in D3.js

I do not manage to update a bar-chart with nested data in D3.js with new data.
I have nested data of the form:
data = [[1,2,3,4,5,6],[6,5,4,3,2,1]];
I managed to visualize the data by first appending a group for every subarray.
In the groups I then add the arrays as data (simplified):
function createGraph(l, svg){
var g = svg.selectAll("g")
.data(l)
.enter().append("g");
var rect = g.selectAll("rect)
.data(function(d){return d;})
.enter().append("rect")
. ...
}
However, when call the function again with different data, nothing happens.
It seems like in the second row, the rects do not get updated.
I have created a full example over at jsBin: http://jsbin.com/UfeCaGe/1/edit?js,output
A little more explanation of Lars' bug-catch, since I'd already started playing around...
The key was in this section of the code:
var group = svg.selectAll("g")
.data(l)
.enter().append("g");
The variable group is assigned the enter selection, not the raw selection. Then in the next line:
var bar = group.selectAll("rect")
.data(function(d){
return d;
});
You end up defining bar as only the rectangles that are children of just-entered groups. So even though you were handling update correctly for the rectangles, that whole section of code wasn't even running. You need to save the group selection before branching the chain to deal with entering groups:
var group = chart.selectAll("g")
.data(dt);
group.enter().append("g");
var bar = group.selectAll("rect")
.data(function(d){
return d;
});
Also, you're missing a j in your function declaration in your update. And you can reduce code duplication by putting your rectangle update code after your rectangle enter code, and then any attributes that get set in the update don't have to be specified for enter. (Some older examples don't use this pattern, because the original versions of d3 didn't automatically transfer newly-entered elements to the main selection.)
// enter
bar.enter().append("rect")
.attr("fill", function(d,i,j){
return colors(j);})
.attr("height", 0);
// update
bar.attr("transform", function(d, i, j) {
x = "translate("+(i*2.2*w+j*w)+",0)";
return x; })
.transition()
.duration(750)
.attr("width", w)
.attr("height", function(d){return d*10;});

d3 transition of areas for shrinking datasets

I'm wondering why the following transition does not work as expected:
in a line chart, users can select different timespans they want the chart to display. If the timespan increases, then the animation is fine: the line moves a bit to the right and the area below that line moves 100% perfect (no gaps or such between line and area).
If on the other hand the timespan decreases then the area transition displays an ugly behavior:
1) initial state
2) change to one week, transition starts
3) transition has a duration of 1 sec
4) end state - no problem here.
I'm using basically the same transition functions for the line:
var valueline = d3.svg.line()
.x(function (d) { return x(d.date); })
.y(function (d) { return y(d.result2); });
and for the area:
var area1 = d3.svg.area()
.x(function (d) { return x(d.date); })
.y0(height)
.y1(function (d) { return y(d.result2); });
I'm not using any explicit enter() or exit() in the area update:
// update area1
svg.selectAll(".area1")
.transition()
.duration(1000)
.attr("d", area1(data));
I could not figure out how to use enter() or exit() in the case of areas, maybe an explicit exit().remove() that would instantly remove unneeded datapoints would solve my problem? But .. how to do that for a line / area??
Thanks for any help!
EDIT
Alright, it was no problem of exit().remove() because for a single line, that doesn't make much sense as I see now, too.
What fixed the transition from large to small dataset was cloning the array of data for the full 4 weeks max-timespan, then giving all datapoints that are outside of the currently visible timespan a y-value of 0 and using this array to feed the areas:
svg.selectAll(".area1")
.data([data2]) // contains data for 4 weeks, with 0's on time outside of current span
.transition()
.duration(1000)
.attr("d", area1);
The x-axis is still feed the array with data of only the currently visible timespan, so it adjusts:
// array "data" contains only data for the desired time horizon, eg 1 week
x.domain(d3.extent(data, function (d) { return d.date; }));

Extending paths in D3 with transition

I've been grappling with issues relating to transitions in D3. Consider this code:
svg.selectAll("path")
.data(data, key)
.enter().append("path")
.attr("d", someFunctionThatReturnsAPath);
});
And I call the following in a setTimeout a few seconds later:
svg.selectAll("path")
.transition()
.duration(2000)
.attr("d", someFunctionThatReturnsADifferentPath);
});
The second call correctly updates the paths but doesn't animate the transition. Why is there no transition when the d attribute is updated in the second call?
Note that the paths are very complex. In both calls, there's a noticeable delay before the paths are actually drawn. Perhaps that's related to the lack of transition?
I'm new to D3, but I've read up on transitions and can't seem to understand why this doesn't behave as I expect it.
Update
Per #Marjancek's answer, I'm providing more details regarding the two called functions.
Here is the definition of someFunctionThatReturnsAPath:
function(d) {
var coordinates = [];
for (var i = d.track.length - 1; i >= 0; i--) {
// We only care about the last 10 elements
if (coordinates.length >= 10)
break;
coordinates.push(d.track[i]);
}
return path({type: "LineString", coordinates: coordinates});
};
And someFunctionThatReturnsADifferentPath:
function(d) {
var coordinates = [];
for (var i = d.track.length - 1; i >= 0; i--) {
// We only care about the last 20 elements
if (coordinates.length >= 20)
break;
coordinates.push(d.track[i]);
}
return path({type: "LineString", coordinates: coordinates});
};
where path is defined as follows (projection is d3.geo.albersUsa()):
var path = d3.geo.path()
.projection(projection);
The objective is that on the second call, the line is extended with 10 newer data points.
If your paths do not have the same number of points, the transitions might not work as expected. Try .attrTween: http://github.com/mbostock/d3/wiki/Transitions#wiki-attrTween There is an example on bl.ocks.org but the site seems to be down at the moment so I can't link to it.
Added on edit: The gist I was thinking of was: https://gist.github.com/mbostock/3916621 the bl.ocks link will be http://bl.ocks.org/mbostock/3916621 when the site is back up.
It is impossible to know without looking at your someFunctionThatReturnsADifferentPath; but I'm guessing that your Different function does not take into account interpolation, from the three parameters it received.
Read the transitions documentation: https://github.com/mbostock/d3/wiki/Transitions

how to animate and play over time in d3.js?

I am a novice while working on d3.js.
I wanted to know how can we Animate some data (eg. Change colors) with respect to time.
eg. Let's say, in Monitoring app, I am projecting cluster data over US Map. Projection is done by drawing a circle and filling it by RED, GREEN or YELLOW color depending on it's status.
When we start monitoring, ideally all circles will be filled with "GREEN" color and then over time color can change to "YELLOW" or "RED" depending on how cluster is behaving.
So if I need to play these color changes over time in some time window, how can it be done ?
If you can point me to any of the similar examples , that will help too ?
Thanks
Take a look at http://mbostock.github.com/d3/tutorial/bar-2.html. Basically you'll need a redraw function that you'll call whenever you want to update your chart. (Note: there is nothing special about the name of this function, you can call it whatever you want.)
You can use setInterval to create a basic timer, this is the rate that your chart will be updated.
setInterval(function() {
redraw(); // call the function you created to update the chart
}, 1500);
Then you define redraw to update the chart data. This is a redraw function for a bar chart, but yours would be similar. You would just be adjusting the color based on the data instead of the y position and height.
function redraw() {
// Update…
chart.selectAll("rect")
.data(data)
.transition()
.duration(1000)
.attr("y", function(d) { return h - y(d.value) - .5; })
.attr("height", function(d) { return y(d.value); });
}
Note that this is a simplified version, I recommend reading the page that I linked above for a more complete example.

Resources