Skip to content

Instantly share code, notes, and snippets.

@HarryStevens
Last active April 29, 2018 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HarryStevens/4608d25b2f424a2e011d7ab9cc804f4e to your computer and use it in GitHub Desktop.
Save HarryStevens/4608d25b2f424a2e011d7ab9cc804f4e to your computer and use it in GitHub Desktop.
Swiftmap Gradient Scheme
license: gpl-3.0

In Swiftmap, continuous schemes are used to map values of data to corresponding visual attributes along a continuum. You can use a continuous scheme to create a gradient color scale. In this example, each polygon is colored, alternatively, according to the horizontal or vertical position of its centroid. Because Swiftmap returns elements as D3 selections, it is easy to animate style transitions.

Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
}
#map {
width: 100%;
height: 100vh;
}
</style>
</head>
<body>
<div id="map"></div>
<!-- D3 modules for d3-request and d3-timer -->
<script src="https://d3js.org/d3-collection.v1.min.js"></script>
<script src="https://d3js.org/d3-dispatch.v1.min.js"></script>
<script src="https://d3js.org/d3-dsv.v1.min.js"></script>
<script src="https://d3js.org/d3-request.v1.min.js"></script>
<script src="https://d3js.org/d3-timer.v1.min.js"></script>
<!-- TopoJSON -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/2.2.0/topojson.min.js"></script>
<script src="https://unpkg.com/swiftmap@0.2.1/dist/swiftmap.min.js"></script>
<script>
var map = swiftmap.map("#map");
var scheme = swiftmap.schemeContinuous()
.from(d => +d.h)
.to(["#a50026", "#d73027", "#f46d43", "#fdae61", "#fee090", "#ffffbf", "#e0f3f8", "#abd9e9", "#74add1", "#4575b4", "#313695"]);
d3.json("cb_2017_us_state_20m.json", (error, counties) => {
map
.projection("albersUsa")
.layerPolygons(counties, d => d.properties.AFFGEOID)
.draw();
var data = topojson.feature(map.layers[0].data, map.layers[0].object).features;
var out = [];
for (var i = 0, l = data.length; i < l; i++){
var d = data[i],
c = map.path.centroid(d);
out.push({
key: d.properties.AFFGEOID,
h: c[0],
v: c[1]
});
}
scheme.data(out, d => d.key);
map.layers[0].polygons
.style("fill", scheme);
var curr_prop = "h";
d3.interval(function(){
var new_prop = curr_prop == "h" ? "v" : "h";
map.layers[0].polygons
.transition().duration(1000)
.style("fill", scheme.from(d => +d[new_prop]));
curr_prop = new_prop;
}, 2000);
window.onresize = () => map.resize();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment