I’m using d3 (more like learning to use) to create a choropleth map. I’ve managed load my data and geojson object and get a map to display, but I would like to add some transitions and the ability for the user to choose their data.
Here’s an example of what I have so far (thanks to github and Mike Bostock’s nice gist viewer):
http://bl.ocks.org/4131166; and
http://gist.github.com/4131166
I had managed to get the colours to change by changing the associated class to the group, but I swapped this to the js version of Cynthia Brewer’s colours as I wanted to transition between them. I also want the colours to change when a different ‘band’ is selected.
I think my problem lies in the updateValues function – it’s doing too much. It’s loading the data, drawing the polygons and populating the colour all in one go.
Is it possible to draw the polygons, and then associate the colour in a separate function?
I had toyed with the idea of adding a:
.attr(“id”, function(d) { return d.id; })
line to the statement which draws the paths, and then somehow using that to link to the data in a separate statement, but I’m not quite sure how I would achieve this – I guess somehow retrieving each path’s id and linking to the data…?
Any help would be gratefully appreciated. Even if that is suggestions on how to improve my code. I’m always happy observe best practice where relevant.
At the core of d3 is the solution. Any time you do
d3.selectAll( ... ).data( ... )what you get is a selection.To affect every node in the selection you chain various d3 functions.
There are two other special functions to chain for sub-selections:
enter()for new nodes &exit()for nodes that no longer exist.If you update the underlying data, then you call the top level
d3.selectAll( ... ).data( ... )and the DOM nodes will be updated according to those three chains: the selection (all nodes), enter (nodes being added), & exit (nodes being removed).So, set your colors on the selection chain, not enter, and they will updated without recreation.