Skip to content

Instantly share code, notes, and snippets.

Forked from mbostock/.block
Created December 2, 2012 11:54
What would you like to do?
World Map
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

Based on Mike Bostock’s World Map, modified to automatically colour countries such that no adjacent countries share the same colour.

This is done by extracting the topology via TopoJSON and greedily picking colours until the constraint is fulfilled.

See also: Graph coloring on Wikipedia.

Update: Greedily colouring is now performed in a single line, thanks to Mike Bostock!

<!DOCTYPE html>
<meta charset="utf-8">
.country {
fill: #ccc;
stroke: #fff;
stroke-width: .5px;
stroke-linejoin: round;
.graticule {
fill: none;
stroke: #000;
stroke-opacity: .3;
stroke-width: .5px;
.graticule.outline {
stroke: #333;
stroke-opacity: 1;
stroke-width: 1.5px;
<script src=""></script>
<script src=""></script>
<script src=""></script>
var width = 960,
height = 500;
var projection = d3.geo.kavrayskiy7(),
color = d3.scale.category20(),
graticule = d3.geo.graticule();
var path = d3.geo.path()
var svg ="body").append("svg")
.attr("width", width)
.attr("height", height);
.attr("class", "graticule")
.attr("d", path);
.attr("class", "graticule outline")
.attr("d", path);
d3.json("readme-world.json", function(error, world) {
var countries = topojson.feature(world, world.objects.countries).features,
neighbors = topojson.neighbors(world.objects.countries.geometries);
.enter().insert("path", ".graticule")
.attr("class", "country")
.attr("d", path)
.style("fill", function(d, i) { return color(d.color = d3.max(neighbors[i], function(n) { return countries[n].color; }) + 1 | 0); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment