Last active
March 4, 2017 23:17
-
-
Save eSlivinski/84c51cc43bc217304cc38a126ac42a33 to your computer and use it in GitHub Desktop.
Mapping Random Data With D3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<!-- Required meta tags --> | |
<meta charset="utf-8"> | |
<style> | |
.state { | |
stroke: rgba(0,0,0,0.4); | |
} | |
circle { | |
fill: orange; | |
fill-opacity: 0.7; | |
stroke-opacity: 1; | |
stroke-width: 1; | |
stroke: yellow; | |
} | |
</style> | |
</head> | |
<body> | |
</body> | |
<script src="http://d3js.org/d3.v4.js"></script> | |
<script> | |
var width = 960; | |
var height = 500; | |
var svg = d3.select("body") | |
.append("svg") | |
.attr('width', width) | |
.attr('height', height) | |
var projection = d3.geoAlbersUsa(); | |
// Path is a function that tells our svg object how to convert our geojson | |
// data into | |
var path = d3.geoPath() | |
.projection(projection); | |
function randomNumber(min, max) { | |
min = Math.ceil(min); | |
max = Math.floor(max); | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
var colorScale = d3.scaleLinear() | |
.domain([0, 1, 2, 3, 4, 5, 6, 7, 8]) | |
.range(['#ffffd9', '#edf8b1', '#c7e9b4', '#7fcdbb', '#41b6c4', '#1d91c0', '#225ea8', '#0c2c84']); | |
d3.json("./us.geojson", function(err, data) { | |
data.features.forEach(function(feature) { | |
// Append the state's 'projected' (screen x/y) to the data object | |
feature.properties.center = path.centroid(feature); | |
}) | |
states = svg.selectAll("path") | |
.data(data.features) | |
.enter().append("path") | |
.attr('class', 'state') | |
.attr("d", path); | |
circles = svg.selectAll("circle") | |
.data(data.features) | |
.enter().append('circle') | |
.attr('cx', function(d) { return d.properties.center[0]; }) | |
.attr('cy', function(d) { return d.properties.center[1]; }) | |
.attr('r', 0); | |
style(); | |
setInterval(style, 3000); | |
}); | |
function style () { | |
states | |
.transition() | |
.duration(1000) | |
.attr('fill', function() { return colorScale(randomNumber(0, 8)) }) | |
.attr('fill-opacity', function() { return Math.random(); }); | |
circles | |
.transition() | |
.duration(1000) | |
.attr('r', function(d) { | |
d.properties.prev_value = d.properties.value || 0; | |
d.properties.value = randomNumber(0, 15); | |
return d.properties.value; | |
}); | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment