Skip to content

Instantly share code, notes, and snippets.

@hungryzi
Last active November 17, 2016 22:33
Show Gist options
  • Save hungryzi/33c6aa7cdc6ad67c1c8f to your computer and use it in GitHub Desktop.
Save hungryzi/33c6aa7cdc6ad67c1c8f to your computer and use it in GitHub Desktop.
Vietname population density by provinces/cities

Visualizing Vietname population density by provinces/cities.

<!DOCTYPE html>
<html>
<head>
<title>Vietnam Population by Provinces</title>
<meta charset="utf-8">
<style>
.boundary {
fill: none;
stroke: #777;
stroke-dasharray: 2,2;
stroke-linejoin: round;
}
path {
stroke: white;
stroke-width: 0.1px;
}
.background {
fill: none;
pointer-events: all;
}
</style>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/queue.v1.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
</head>
<body>
<script src="population_density_map.js"></script>
</body>
</html>
var width = 960,
height = 1160,
centered;
var densityById = d3.map();
var scale = d3.scale
.linear()
.domain([0,3731])
.range([0,1]);
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
queue()
.defer(d3.json,"vietnam_adm2.json")
.defer(d3.csv,
"vietnam_population_by_province.csv",
function(d){
densityById.set(d.id,d.density);
}
)
.await(ready);
function ready(error, topojsonFile, data) {
svg.append("rect")
.attr("class","background")
.attr("width",width)
.attr("height",height)
.on("click", clicked);
var projection = d3.geo.mercator()
.center([107,11])
.scale(2490)
.translate([width/2,height/2]);
var path = d3.geo.path().projection(projection);
var provinces = topojson.feature(topojsonFile, topojsonFile.objects.VNM_adm2).features;
var g = svg.append("g");
g.append("g")
.selectAll("path")
.data(provinces)
.enter()
.append("path")
.attr("fill", function(d) { console.log(d); return "rgba(0, 0, 255, " + scale(densityById.get(d.id)) + ")"; })
.attr("id",function(d) { return d.id;})
.attr("d",path)
.on("click",clicked);
function clicked(d) {
var x, y, k;
if ( d && centered !== d) {
var centroid = path.centroid(d);
x = centroid[0];
y = centroid[1];
k = 9;
centered = d;
}
else {
x = width/2;
y = height/2;
k = 1;
centered = null;
}
g.selectAll("path")
.classed("active", centered && function(d) { return d === centered; });
g.transition()
.duration(750)
.attr("transform","translate(" + width/2 + "," + height/2 + ")scale(" + k + ")translate("+ -x +"," + -y + ")")
.style("stroke-width", 1.5/k + "px");
}
}
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment