Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
(function(){
var width = 660,
height = 460;
var edById = {},
nameById = {};
var formatNum = d3.format(",.0f"),
formatPercent = d3.format(",.0%");
var projection = d3.geo.albersUsa()
.scale(850).translate([330,220]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("#us-smartz-viz").append("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", "0 0 660 460")
.attr("perserveAspectRatio", "xMinYMid");
d3.selectAll("#smartz-input").on("change", updateMap);
queue()
.defer(d3.json, "/public/data/us.json")
.defer(d3.tsv, "/public/data/census-data.tsv")
.await(ready);
function ready(error, us, census) {
census.forEach(function(d) {
edById[d.fips] = +d.EDU685211;
nameById[d.fips] = d.location.replace(";",",");
});
svg.append("g")
.attr("class", "counties")
.selectAll("path")
.data(topojson.feature(us, us.objects.counties).features)
.enter().append("path")
.attr("d", path)
.on("mouseover", displayCountyNums)
.on("mouseout", function() { $('#countySelected').text(''); });
svg.append("path")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a.id !== b.id; }))
.attr("class", "states")
.attr("d", path);
}
function updateMap() {
var val = $('#smartz-input').val(),
num_counties = _.filter(edById, function(d){ return d >= val; }).length,
county_percent = num_counties / 3195.0;
$('#inputVal').text(val + '%');
$('#numCounties').text(formatNum(num_counties));
$('#countyPercent').text(formatPercent(county_percent));
svg.selectAll('.counties path')
.style("fill", function(d) { return edById[d.id] >= val ? "steelblue" : "#ccc"; });
}
function displayCountyNums() {
var d = this.__data__;
if (nameById[d.id] != undefined) {
$('#countySelected').text(nameById[d.id] + ': ' + formatNum(edById[d.id]) + '%');
}
}
// making viz responsive for smaller windows
var chart = $("#us-smartz-viz svg"),
aspect = chart.width() / chart.height(),
container = chart.parent();
$(window).on("resize", function() {
var targetWidth = container.width();
chart.attr("width", targetWidth);
chart.attr("height", Math.round(targetWidth / aspect));
}).trigger("resize");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment