Most basic choropleth map in d3.js

This post describes how to build a very basic choropleth map of the world with d3.js. Note that the same kind of code would work with any geospatial data stored in geojson format. You can see many other examples in the choropleth map section of the gallery.

Choropleth map section


  • First of all, see the background map section to understand the basics of mapping with d3.

  • Map shows the world population per country in 2005. Data comes from here, stored here

  • You must have a common id between the geospatial file and the data. Here it is the 'id' field.

  • Here a threshold color scale is used. Learn more about color scale here
<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src=""></script>
<script src=""></script>
<script src=""></script>

<!-- Create an element where the map will take place -->
<svg id="my_dataviz" width="400" height="300"></svg>


// The svg
var svg ="svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height");

// Map and projection
var path = d3.geoPath();
var projection = d3.geoMercator()
  .translate([width / 2, height / 2]);

// Data and color scale
var data =;
var colorScale = d3.scaleThreshold()
  .domain([100000, 1000000, 10000000, 30000000, 100000000, 500000000])

// Load external data and boot
  .defer(d3.json, "")
  .defer(d3.csv, "", function(d) { data.set(d.code, +d.pop); })

function ready(error, topo) {

  // Draw the map
      // draw each country
      .attr("d", d3.geoPath()
      // set the color of each country
      .attr("fill", function (d) { = data.get( || 0;
        return colorScale(;


Related blocks →

  • World Choropleth - link

  • Projection Transitions - link