d3: confusion about selectAll() when creating new elements - javascript

I am new to d3 and am using 'Interactive Data Visualization for the Web' by Scott Murray (which is great btw) to get me started. Now everything I saw so far works as described but something got me confused when looking at the procedure to create a new element. Simple example (from Scott Murray):
svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle");
The name "circle" is used for the selectAll which returns an empty selection (which is ok as I learned). Then circles are appended by putting the same name into the .append. Great!
Now what got me confused was what happens when you want to do the same thing again. So you have a second dataset and want to generate new circles in the same way. Using the same code just replacing the dataset will obviously not work as the selectAll("circle") will not return an empty selection anymore. So I played around and found out that I can use any name in the selectAll and even leave it empty like this: selectAll()
Scott Murrays examples always just use one type (circle, text, etc.) per dataset. Finally I found in the official examples something like
svg.selectAll("line.left")
.data(dataset)
.enter()
.append("line")
.attr ...
svg.selectAll("line.right")
.data(dataset)
.enter()
.append("line");
.attr ...
Now my question: How is this entry in selectAll("ENTRY") really used? Can it be utilized later to again reference those elements in any way or is it really just a dummy name which can be chosen in any way and just needs to return an empty selection? I could not find this entry anywhere in the resulting DOM or object structure anymore.
Thank you for de-confusing me.

What you put in the selectAll() call before the call to .data() really only matters if you're changing/updating what's displayed. Imagine that you have a number of circles already and you want to change their positions. The coordinates are determined by the data, so initially you would do something like
svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", function(d) { return d; })
.attr("cy", function(d) { return d; });
Now your new data has the same number of elements, but different coordinates. To update the circle positions, all you need to do is
svg.selectAll("circle")
.data(newData)
.attr("cx", function(d) { return d; })
.attr("cy", function(d) { return d; });
What happens is that D3 matches the elements in newData to the existing circles (what you selected in selectAll). This way you don't need to append the circles again (they are there already after all), but only update their coordinates.
Note that in the first call, you didn't technically need to select circles. It is good practice to do so however just to make clear what you're trying to do and to avoid issues with accidentally selecting other elements.
You can find more on this update pattern here for example.

Related

Basic d3: why can you select things that don't exist yet?

I've been learning about d3, and I'm a bit confused about selecting. Consider the following example:
http://bl.ocks.org/mbostock/1021841
Specifically, let's look at this line:
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 8)
.style("fill", function(d, i) { return fill(i & 3); })
.style("stroke", function(d, i) { return d3.rgb(fill(i & 3)).darker(2); })
.call(force.drag)
.on("mousedown", function() { d3.event.stopPropagation(); });
In the documentation it says, "A selection is an array of elements pulled from the current document." I interpret this to mean that svg.selectAll(.node) creates an array of elements of class .node pulled from the current document, but as far as I can tell there are no such elements! Unless I'm confused - and I'm almost certain that I am - the only place in the document where something is given the class "node" is after the selection has already occurred (when we write .attr("class", "node")).
So what is going on here? What does svg.selectAll(".node") actually select?
Although, at first sight, this may look like a simple and silly question, the answer to it is probably the most important one for everyone trying to do some serious work with D3.js. Always keep in mind, that D3.js is all about binding data to some DOM structure and providing the means of keeping your data and the document in sync.
Your statement does exactly that:
Select all elements having class node. This may very well return an empty selection, as it is in your case, but it will still be a d3.selection.
Bind data to this selection. Based on the above mentioned selection this will, on a per-element basis, compute a join checking if the new data is a) not yet bound to this selection, b) has been bound before, or c) was bound before but is not included in the new data any more. Depending on the result of this check the selection will be divided into an enter, an update, or an exit selection, respectively.
Because your selection was empty in the first place. All data will end up in the enter selection which is retrieved by calling selection.enter().
You are now able to append your new elements corresponding to the newly bound data by calling selection.append() on the enter selection.
Have a look at the excellent article Thinking with Joins by Mike Bostock for a more in-depth explanation of what is going on.

Drawing multiple sets of multiple lines on a d3.js chart

I have a d3 chart that displays two lines showing a country's imports and exports over time. It works fine, and uses the modular style described in 'Developing a D3.js Edge' so that I could quite easily draw multiple charts on the same page.
However, I now want to pass in data for two countries and draw imports and exports lines for both of them. After a day of experimentation, and getting closer to making it work, I can't figure out how to do this with what I have. I've successfully drawn multi-line charts with d3 before, but can't see how to get there from here.
You can view what I have here: http://bl.ocks.org/philgyford/af4933f298301df47854 (or the gist)
I realise there's a lot of code. I've marked with "Hello" the point in script.js where the lines are drawn. I can't work out how to draw those lines once for each country, as opposed to just for the first one, which is what it's doing now.
I'm guessing that where I'm applying data() isn't correct for this usage, but I'm stumped.
UPDATE: I've put a simpler version on jsfiddle: http://jsfiddle.net/philgyford/RCgaL/
The key to achieving what you want are nested selections. You first bind the entire data to the SVG element, then add a group for each group in the data (each country), and finally get the values for each line from the data bound to the group. In code, it looks like this (I've simplified the real code here):
var svg = d3.select(this)
.selectAll('svg')
.data([data]);
var g = svg.enter().append('svg').append('g');
var inner = g.selectAll("g.lines").data(function(d) { return d; });
inner.enter().append("g").attr("class", "lines");
inner.selectAll("path.line.imports").data(function(d) { return [d.values]; })
.enter().append("path").attr('class', 'line imports')
.attr("d", function(d) { return imports_line(d); });
The structure generated by this looks like svg > g > g.lines > path.line.imports. I've omitted the code for the export line here -- that would be below g.lines as well. Your data consists of a list of key-value pairs with a list as value. This is mirrored by the SVG structure -- each g.lines corresponds to a key-value pair and each path to the value list.
Complete demo here.
The point is that you're thinking to imperative. That's why you have so much code. I really can't put it better than Mike Bostock, you have to start Thinking with Joins:
svg.append("circle")
.attr("cx", d.x)
.attr("cy", d.y)
.attr("r", 2.5);
But that’s just a single circle, and you want many circles: one for each data point. Before you bust out a for loop and brute-force it, consider this mystifying sequence from one of D3’s examples.
Here data is an array of JSON objects with x and y properties, such as: [{"x": 1.0, "y": 1.1}, {"x": 2.0, "y": 2.5}, …].
svg.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 2.5);
I'll leave translating this example to the "from one line to many lines" as an excerxise.

Updating a pie chart with a new data set with more values

I'm relatively new to D3 and have been following a few pie chart tutorials.
Namely the Mike Bostock Tutorials. http://bl.ocks.org/mbostock/1346410
But I have question about a donut chart updating from one data set to another with the 2nd data set having much more values than the first.
I have attempted this numerous times through an update function but no luck, I'll keep it simple and give a hypothetical example , lets say my first data set had 5 values
[1,2,3,4,5]
and my second data set had 10 values
[1,2,3,4,5,6,7,8,9,10]
only 5 values of the new data set would be depicted on the arcs after the dynamic update. It's like the pie is fixed with only 5 arc sections being able to display 5 values of the new dataset.
Any help would be appreciated as its been stumbling around with the idea for awhile!
The key to making it work with data of different size is to handle the .enter() and .exit() selections. This tutorial goes into more detail, but briefly the enter selection represents data for which no DOM elements exist (e.g. in the case where you pass in more data), the update selection (which you're already handling) represents data for which DOM elements exist and the exit selection DOM elements for which no data exists anymore (e.g. when you have more elements to start with).
So in your change function, you would need to do something like this.
function change() {
clearTimeout(timeout);
var path = svg.datum(data).selectAll("path")
.data(pie);
path.enter().append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc)
.each(function(d) { this._current = d; }); // add the new arcs
path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
path.exit().remove(); // remove old arcs
}
This assumes that you're updating your data variable as you suggest above instead of getting a different value from the existing data structure as in the example.
Here I made a simple update that triggers when you click the text above the pie chart: JsFiddle
The main thing happening is all the data is updated when the .on("click") event triggers, so the chart gets updated like so:
d3.select("#update")
.on("click", function (d) {
data = [1,2,3,4,5,6,7,8,9,10];
vis.data([data]);
arc = d3.svg.arc().outerRadius(r);
pie = d3.layout.pie().value(function(d){return d; });
arcs.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice")
.append("svg:path")
.attr("fill", function(d, i){return color(i);}).attr("d", arc);
});

Map does not render completely in d3.js

I am creating a globe on which I plot a number of locations. Each location is identified with a small circle and provides information via a tooltip when the cursor hovers over the circle.
My problem is the global map renders incompletely most of the time. That is various countries do not show up and the behavior of the code changes completely at this point. I say most of the time because about every 5th time i refresh the browser it does render completely. I feel like I either have a hole in my code or the JSON file has a syntax problem that confuses the browser.
btw: I have the same problem is FF, Safari, and Chrome. I am using v3 of D3.js
Here is the rendering code:
d3.json("d/world-countries.json", function (error, collection) {
map.selectAll("path")
.data(collection.features)
.enter()
.append("svg:path")
.attr("class", "country")
.attr("d", path)
.append("svg:title")
.text( function(d) {
return d.properties.name; });
});
track = "countries";
d3.json("d/quakes.json", function (error, collection) {
map.selectAll("quakes")
.data(collection.features)
.enter()
.append("svg:path")
.attr("r", function (d) {
return impactSize(d.properties.mag);
})
.attr("cx", function (d) {
return projection(d.geometry.coordinates)[0];
})
.attr("cy", function (d) {
return projection(d.geometry.coordinates)[1];
})
.attr("class", "quake")
.on("mouseover", nodehi)
.on("mouseout", nodelo)
.attr("d", path)
.append("svg:title")
.text( function(d) {
var tip = d.properties.description + " long "+ (d.geometry.coordinates)[0] + " lat " + (d.geometry.coordinates)[1];
return tip
});
});
Any thoughts would be appreciated...
The reason you're seeing this behaviour is that you're doing two asynchronous calls (to d3.json) that are not independent of each other because of the way you're selecting elements and binding data to them. By the nature of asynchronous calls, you can't tell which one will finish first, and depending on which one does, you see either the correct or incorrect behaviour.
In both handler functions, you're appending path elements. In the first one (for the world file), you're also selecting path elements to bind data to them. If the other call finished first, there will be path elements on the page. These will be matched to the data that you pass to .data(), and hence the .enter() selection won't contain all the elements you're expecting. This is not a problem if the calls finish the other way because you're selecting quake elements in the other handler.
There are several ways to fix this. You could either assign identifying classes to all your paths (which you're doing already) and change the selectors accordingly -- in the first handler, do .selectAll("path.country") and in the second .selectAll("path.quake").
Alternatively, you could nest the two calls to d3.json such that the second one is only made once the first one is finished. I would do both of those to be sure when elements are drawn, but for performance reasons you may still want to make the two calls at the same time.

Multiple paths with d3.js and google maps API

I'm trying to add an overlay of some paths defined by GeoJSON data using the Google Maps API. I started by using the examples in this thread and it worked fine with my data -- until I tried using two different paths. The paths need to be rendered with different colors, so I can't combine the datasets.
I've encountered an issue where not all of the paths will render fully. Here's the gist of what I'm attempting to do:
path2 = d3.geo.path().projection(googleMapProjection);
path4 = d3.geo.path().projection(googleMapProjection);
svg.selectAll("path")
.data(line2_geoJson.features)
.attr("d", path2) // update existing paths
.attr("stroke", "red")
.enter().append("svg:path");
svg.selectAll("path")
.data(line4_geoJson.features)
.attr("d", path4) // update existing paths
.attr("stroke", "green")
.enter().append("svg:path");
To show some examples:
http://jsfiddle.net/HWxKu/ -- Notice that the red path renders, but the green path never shows up. (Zoom in a bit.)
http://jsfiddle.net/X644x/ -- The only different is that I switched the order of the two svg.selectAll statements. The green path mostly renders, and bits of the red path render after you zoom in a bit.
Can anyone explain what might be happening? My thought is that either the Google Maps API is imposing some kind of limit on the overlay (perhaps a timeout?), or is something asynchronous happening here? I'm a novice to d3, so any explanation is greatly appreciated.
You're using the enter() selection wrong. The first set of statements to set "d" and "stroke" doesn't do anything at all because there are no paths yet. You need to put these after appending the new elements.
The second problem is that with the second statement, you're overwriting the first paths. By default, D3 matches new to existing data by the array index. That is, the first new feature is matched to the first existing path and so on. You need to supply a function to tell D3 how to match.
The code I think you want looks like this.
svg.selectAll("path")
.data(line2_geoJson.features, function(d) { return d.properties.route_id; })
.enter().append("path")
.attr("d", path2)
.attr("stroke", "red");
svg.selectAll("path")
.data(line4_geoJson.features, function(d) { return d.properties.route_id; })
.enter().append("path")
.attr("d", path4)
.attr("stroke", "green");

Categories

Resources