d3-exploder
What is this?
This is a tiny d3 extension that lets you easily move and resize geographic features rendered with d3 and topojson.
Why would I want this?
Say you have a map of the US (like above) and you want to gratuitously transition the map into a scatter plot where the states are the points. This will let you do that. To see this in action, click the "scatter" button above.
How can I use this?
You can install via...
npm install d3-exploder
And then import within javascript
import { exploder } from 'd3-exploder';
var myExploder = exploder();
or include via a script tag
<script src="http://d3js.org/d3.v4.min.js" charset="utf-8"></script>
<script src="http://d3js.org/topojson.v2.min.js"></script>
<script src="d3-exploder.min.js"></script>
Next, create a map with some geographic features... and then create an exploder function and call it!
var width = 960,
height = 500;
var projection = d3.geoAlbersUsa().scale(width);
var path = d3.geoPath()
.projection(projection);
var svg = d3.select("#map").append("svg")
.attr("width", width)
.attr("height", height);
var g = svg.append("g");
d3.json("us.json", function(error, us) {
var state_features = topojson.feature(
us, us.objects.states
).features;
var states = g.append("g")
.attr("id", "states")
.selectAll("path")
.data(state_features)
.enter().append("path")
.attr("d", path);
// Here is the magic!
// This exploder will create a grid of the states
// when called on a featurelist selection
var exploder = d3.exploder()
// use the same projection as the map
.projection(projection)
// provide a function to determine the size
// of each feature when called
.size(function(d, i) { return 40; })
// provide a function to determine the
// new (grid) positions of the features
// -> returns an [x, y] array (in pixels)
.position(function(d, i) {
var px = Math.max(0, width - 9*60)/2
return [px + (i%10)*60, 70 + Math.floor(i/10)*60];
})
//
// transition to the grid
//
states
.transition()
.duration(500)
.call(exploder);
});