D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
rcrocker13
Full window
Github gist
Intermediate D3: Week 4
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Choropleth</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script> <style type="text/css"> body { background-color: white; } svg { background-color: gray; box-shadow: 3px 3px 5px #333; } </style> </head> <body> <script type="text/javascript"> //Year of CO2 data to map var year = "2010"; //Width and height var w = 960; var h = 500; //Define map projection var projection = d3.geo.albersUsa() .translate([w / 2, h / 2]) .scale([600]); //Define path generator var path = d3.geo.path() .projection(projection); //Define quantize scale to sort data values into buckets of color //Colors by Cynthia Brewer (colorbrewer2.org), YlOrRd var color = d3.scale.quantize() .range([ "#f1eef6", "#bdc9e1", "#74a9cf", "#2b8cbe", "#045a8d" ]); //Create SVG var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); //Load in CO2 data d3.csv("mass-shootings.csv", function(data) { data = d3.nest() .key(function(d) { return d.state; }) .rollup(function(v) { return d3.sum(v, function(d) { return d.victims; }); }) .entries(data); //Set input domain for color scale color.domain([ d3.min(data, function(d) { return +d.values; }), d3.max(data, function(d) { return +d.values; }) ]); //Load in GeoJSON data d3.json("states.json", function(json) { //Merge the CO2 data and GeoJSON into a single array // //Loop through once for each CO2 data value for (var i = 0; i < data.length; i++) { //Grab country name var dataState = data[i].key; //Grab data value, and convert from string to float var dataValue = +data[i].values; //Find the corresponding country inside the GeoJSON for (var j = 0; j < json.features.length; j++) { //We'll check the official ISO country code var jsonState = json.features[j].properties.name; if (dataState == jsonState) { //Copy the data value into the GeoJSON json.features[j].properties.values = dataValue; //Stop looking through the JSON break; } } } //Bind data and create one path per GeoJSON feature svg.selectAll("path") .data(json.features) .enter() .append("path") .attr("d", path) .style("fill", function(d) { //Get data value var values = d.properties.values; if (values) { //If value exists… return color(values); } else { //If value is undefined… return "gray"; } }) .style("stroke", "#ffffff"); }); //End d3.json() }); //End d3.csv() </script> </body> </html>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js