My recursive function is too fast, to animate paths - javascript

I'm visualising voyages on a map with D3.js' path. My data is in a JSON file like the following format:
[{"begin_date":1519,"trips":[[-13.821772,14.294839],[-9.517688,-7.958521],[0.598434,-34.704567],[18.374673,-86.850335]]},
{"begin_date":1549,"trips":[[12.821772,-16.294839],[5.517688,-20.958521],[13.598434,-54.704567],[18.374673,-86.850335]]},
{"begin_date":1549,"trips":[[12.821772,-16.294839],[5.517688,-20.958521],[13.598434,-54.704567],[18.374673,-86.850335]]}]
As can be seen, sometimes there are multiple voyages for a year. The following recursive function works:
d3.json("data/output.json", function(error, trips) {
if (error) throw error
var nest = d3.nest()
.key(function(d){
return d.begin_date;
})
.entries(trips)
var trip = svg.selectAll(".voyage");
// Add the year label; the value is set on transition.
var label = svg.append("text")
.attr("class", "year label")
.attr("text-anchor", "end")
.attr("y", height - 400)
.attr("x", width+150)
.text(function(d) {return d});
var pnt = 0;
doTransition();
function doTransition() {
trip.data(nest[pnt].values).enter()
.append("path")
.attr("class", "voyage")
.style("stroke", colorTrips)
.attr('d', function(d) {label.text(d.begin_date); return lineGen(d.trips.map(reversed).map(projection))})
.call(function transition(path) {
path.transition()
.duration(500)
.attrTween("stroke-dasharray", tweenDash)
.each("end", function(d) {
d3.selectAll(".voyage")
.remove()
pnt++;
if (pnt >= nest.length){return;}
doTransition();
})
})
}
Some voyages plot as they should
However some of them, are never plotted (I can see in the log) and it jumps from year 1545-1569 despite there being data points in between. I suspect it is due to the recursive function calling itself before the transition is finished. But I am also not sure, in the slightest.
Hope it is sufficient, I am new to D3.js, and suddenly found myself out of depth.

Related

D3 update pattern drawing the same element twice

I’ve created a line graph in D3. To ensure the line doesn’t overlap the y-axis, I have altered the range of the x-axis. As a result of this, there is a gap between the x-axis and the y-axis which I am trying to fill with another line.
The rest of the graph uses the D3 update pattern. However, when I try to use the pattern on this simple line, two path elements are drawn (one on top of the other). I have tried numerous solutions to correct this issue but I’m not having any luck. Does anyone have any suggestions?
The code below is what is drawing two of the same path elements
var xAxisLineData = [
{ x: margins.left , y: height - margins.bottom + 0.5 },
{ x: margins.left + 40, y: height - margins.bottom + 0.5 }];
var xAxisLine = d3.line()
.x(function (d) { return d.x; })
.y(function (d) { return d.y; });
var update = vis.selectAll(".xAxisLine")
.data(xAxisLineData);
var enter = update.enter()
.append("path")
.attr("d", xAxisLine(xAxisLineData))
.attr("class", "xAxisLine")
.attr("stroke", "black");
Your problem is here:
var update = vis.selectAll(".xAxisLine")
.data(xAxisLineData);
this is a null selection, assuming there are no elements with the class xAxisLine, which means that using .enter().append() will append one element for each item in the xAxisLineData array.
You want to append one path per set of points representing a line, not one path for each in a set of points representing a line.
You really just want one line to be drawn, so you could do:
.data([xAxisLineData]);
or, place all the points in an array when defining xAxisLineData
Now you are passing a data array to the selection that contains one item: an array of points - as opposed to many items representing individual points. As the data array has one item, and your selection is empty, using .enter().append() will append one element:
var svg = d3.select("body").append("svg").attr("width",500).attr("height",400);
var lineData = [{x:100,y:100},{x:200,y:200}]
var xAxisLine = d3.line()
.x(function (d) { return d.x; })
.y(function (d) { return d.y; });
var colors = ["steelblue","orange"];
var line = svg.selectAll(null)
.data([lineData])
.enter()
.append("path")
.attr("d", xAxisLine(lineData))
.attr("class", "xAxisLine")
.attr("stroke-width", function(d,i) { return (1-i) * 10 + 10; })
.attr("stroke", function(d,i) { return colors[i]; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
Compare without using an array to hold all the data points:
var svg = d3.select("body").append("svg").attr("width",500).attr("height",400);
var lineData = [{x:100,y:100},{x:200,y:200}]
var xAxisLine = d3.line()
.x(function (d) { return d.x; })
.y(function (d) { return d.y; });
var colors = ["steelblue","orange"];
var line = svg.selectAll(null)
.data(lineData)
.enter()
.append("path")
.attr("d", xAxisLine(lineData))
.attr("class", "xAxisLine")
.attr("stroke-width", function(d,i) { return (1-i) * 10 + 10; })
.attr("stroke", function(d,i) { return colors[i]; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
But, we can make one last change. Since each item in the data array is bound to the element, we can reference the datum, not the data array xAxisLineData, which would make adding multiple lines much easier:
.attr("d", function(d) { return xAxisLine(d) })
Note in the demo below that the variable xAxisLineData is defined as an array of arrays of points, or an array of multiple lines.
var svg = d3.select("body").append("svg").attr("width",500).attr("height",400);
var lineData = [[{x:100,y:100},{x:200,y:200}],[{x:150,y:150},{x:260,y:150}]]
var xAxisLine = d3.line()
.x(function (d) { return d.x; })
.y(function (d) { return d.y; });
var colors = ["steelblue","orange"];
var line = svg.selectAll(null)
.data(lineData)
.enter()
.append("path")
.attr("d", function(d) { return xAxisLine(d) }) // use the element's datum
.attr("class", "xAxisLine")
.attr("stroke-width", function(d,i) { return (1-i) * 10 + 10; })
.attr("stroke", function(d,i) { return colors[i]; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

D3 chart can't update -- enter and exit property of selection both empty

I'm trying to make a scatter plot using a .json file. It will let the user to select which group of data in the json file to be displayed. So I'm trying to use the update pattern.
The following code will make the first drawing, but every time selectGroup() is called(the code is in the html file), nothing got updated. The console.log(selection) did come back with a new array each time, but the enter and exit property of that selection is always empty.
Can anyone help me take a look? Thanks a lot!
var margin = {
top: 30,
right: 40,
bottom: 30,
left: 40
}
var width = 640 - margin.right - margin.left,
height = 360 - margin.top - margin.bottom;
var dataGroup;
var groupNumDefault = "I";
var maxX, maxY;
var svg, xAxis, xScale, yAxis, yScale;
//select and read data by group
function init() {
d3.json("data.json", function (d) {
maxX = d3.max(d, function (d) {
return d.x;
});
maxY = d3.max(d, function (d) {
return d.y;
});
console.log(maxY);
svg = d3.select("svg")
.attr("id", "scatter_plot")
.attr("width", 960)
.attr("height", 500)
.append("g")
.attr("id", "drawing_area")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//x-axis
xScale = d3.scale.linear().range([0, width]).domain([0, maxX]);
xAxis = d3.svg.axis()
.scale(xScale).orient("bottom").ticks(6);
//y-axis
yScale = d3.scale.linear().range([0, height]).domain([maxY, 0]);
yAxis = d3.svg.axis().scale(yScale).orient("left").ticks(6);
svg.append("g")
.attr("class", "x_axis")
.attr("transform", "translate(0," + (height) + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y_axis")
.call(yAxis);
});
selectGroup(groupNumDefault);
}
//update data
function selectGroup(groupNum) {
d3.json("/data.json", function (d) {
dataGroup = d.filter(function (el) {
return el.group == groupNum;
});
console.log(dataGroup);
drawChart(dataGroup);
});
}
//drawing function
function drawChart(data) {
var selection = d3.select("svg").selectAll("circle")
.data(data);
console.log(selection);
selection.enter()
.append("circle")
.attr("class", "dots")
.attr("cx", function (d) {
console.log("updating!");
return xScale(d.x);
})
.attr("cy", function (d) {
return yScale(d.y);
})
.attr("r", function (d) {
return 10;
})
.attr("fill", "red");
selection.exit().remove();
}
init();
The problem here is on two fronts:
Firstly, your lack of a key function in your data() call means data is matched by index (position in data array) by default, which will mean no enter and exit selections if the old and current datasets sent to data() are of the same size. Instead, most (perhaps all) of the data will be put in the update selection when d3 matches by index (first datum in old dataset = first datum in new dataset, second datum in old dataset = second datum in new dataset etc etc)
var selection = d3.select("svg").selectAll("circle")
.data(data);
See: https://bl.ocks.org/mbostock/3808221
Basically, you need your data call adjusted to something like this (if your data has an .id property or anything else that can uniquely identify each datum)
var selection = d3.select("svg").selectAll("circle")
.data(data, function(d) { return d.id; });
This will generate enter() and exit() (and update) selections based on the data's actual contents rather than just their index.
Secondly, not everything the second time round is guaranteed be in the enter or exit selections. Some data may be just an update of existing data and not in either of those selections (in your case it may be intended to be completely new each time). However, given the situation just described above it's pretty much guaranteed most of your data will be in the update selection, some of it by mistake. To show updates you will need to alter the code like this (I'm assuming d3 v3 here, apparently it's slightly different for v4)
selection.enter()
.append("circle")
.attr("class", "dots")
.attr("r", function (d) {
return 10;
})
.attr("fill", "red");
// this new bit is the update selection (which includes the just added enter selection
// now, the syntax is different in v4)
selection // v3 version
// .merge(selection) // v4 version (remove semi-colon off preceding enter statement)
.attr("cx", function (d) {
console.log("updating!");
return xScale(d.x);
})
.attr("cy", function (d) {
return yScale(d.y);
})
selection.exit().remove();
Those two changes should see your visualisation working, unless of course the problem is something as simple as an empty set of data the second time around which would also explain things :-)

D3.js multigraph: Output Relative Y Value of a Slider Value on the X-Axis, and match to SVG point location

I have a 3 line graph processed from a .tsv file into this semi-interactive line-graph: http://infinitepartycles.com/plotGraphMultipleTSV/
Code here:
http://codepen.io/ferret/pen/BoxKyX
You'll notice the Y values markers "matching" to the X values are wrong; that white # is the printout of < y(value) >.
I want it to output the relative Y value to whatever the slider value is, but when I dig into the array for any line, I get undefined...Any ideas?
Sidenote: the lines output Here:
var p1 = city.append("path") //Add the 3 coloured lines for transport type
.attr("class", "line")
.attr("id", function(d) { return d.name; }) // ID of transport type
.attr("d", function(d) { return line(d.values); }); //data of all Y values
Why can't I get a value if I console.log(d) here?
I think you are making your brushed event too complicated. It could be re-written as:
function brushed() {
var value = brush.extent()[0].toFixed(0);
if (d3.event.sourceEvent) { // not a programmatic event
value = x.invert(d3.mouse(this)[0]).toFixed(0);
brush.extent([value, value]);
}
handle.attr("cx", x(value));
if (value <= 1) value = 1;
circleBus
.attr("opacity", 1)
.attr("cx", x(value))
.attr("cy", y(transports[0].values[value-1].people));
circlePlane
.attr("opacity", 1)
.attr("cx", x(value))
.attr("cy", y(transports[1].values[value-1].people));
circleTrain
.attr("opacity", 1)
.attr("cx", x(value))
.attr("cy", y(transports[2].values[value-1].people));
}
See example here.

Transition for a line chart in D3

I have built a multi series line chart using the D3 library. I have been trying to work on animating the line chart so I can give out one line at a time and not all 5 of them together. Can anybody give me some ideas as to how I can go about with this? I have tried using transition() but I seem to be using it wrong. This is what I have done so far -
var city = svg.selectAll(".city")
.data(years)
.enter().append("g")
.attr("class", "city");
city.append("path")
.attr("class", "line");`
d3.transition().selectAll(".line")
.duration(500)
.ease("linear")
.attr("d", function(d){return line(d.values); })
.style("stroke", function(d) {return color(d.name); })
.attrTween("d",pathTween);
function pathTween() {
var interpolate = d3.scale.quantile()
.domain([0,1])
.range(d3.range(1,years.length+1));
return function(t){
return line(data.slice(0,interpolate(t)));
};
D3 transitions have a .delay() method that allows you to set a delay before each transition starts. In your case (having each line start separately) it would look like this:
d3.transition().selectAll(".line")
.duration(500)
.delay(function(d, i) { return i * 500; })
.ease("linear")
.attr("d", function(d){return line(d.values); })
.style("stroke", function(d) {return color(d.name); });
This takes the index of each line (i) and offsets the start of the transition depending on that.

Overlay circle, text, etc. over d3.js multi-series lines

I have the multi series line chart code with slight modifications to support my data set. This is what I wish to do, and no solution I have looked at seems to function properly for me. I wish to overlay some element (circle, rectange, hidden, whichever) over each point on the line such that I could then attach a mouseover element on that point to display a box with data containing the d.time, d.jobID and how much that differs from an average. If possible, I would like the solution to only do this to the main line (the varying line) rather than the two lines drawn to represent the average. Here, I have a picture of the graph as-is for visual inspection. If that doesn't work, I have also attached it.
I have posted a bit the code below:
d3.tsv("values.tsv", function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "time" && key !== "jobID"; }));
data.forEach(function(d) {
d.time = parseDate(d.time);
d.jobID = parseInt(d.jobID);
});
var points = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {time: d.time, jobID: d.jobID, value: parseFloat(d[name],10)};
})
};
});
....
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 7)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("mbps");
var point = svg.selectAll(".point")
.data(points)
.enter().append("g")
.attr("class", "point");
point.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
point.append("text")
.datum(function(d) { return {name: d.name, jobID: d.jobID, value: d.values[d.values.length - 1]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.time) + "," + y(d.value.value) + ")"; })
.attr("x", 6)
.attr("dy", ".7em")
.text(function(d) { return d.name; });
});
I have already tried the following code just to see if it worked with my implementation:
point.append("svg:circle")
.attr("stroke", "black")
.attr("fill", function(d, i) { return "black" })
.attr("cx", function(d, i) { return x(d.time) })
.attr("cy", function(d, i) { return y(d.value) })
.attr("r", function(d, i) { return 3 });
D3.JS seems like a pretty awesome piece of work, and I'm fortunate to have it.
EDIT: jsfiddle
The trick is to pass the data again to a selection and then operate on the result of that. Have a look at Mike's tutorial for some background and examples.
I've changed your jsfiddle to add circles here. Attaching svg:title elements or doing something else to show more information should be straightforward. Note that I modified your code to create the data points slightly to include the name with each element. This way, only one additional level of selections is necessary (treat all the points the same and add them in a single pass). The cleaner way to solve this from a code design point of view would be to have 2 additional levels -- first have a selection for the points for an individual line (and add an svg:g element to group them) and then add the points within this group. This would make the code quite a bit more complex and difficult to understand though.

Categories