Choropleth map with hover effect in d3.js

It is a very common practice to add hover effects on choropleth maps with d3.js. Here, the hovered regions has its opacity increased when all other regions are made more transparent.

Choropleth map section


  • First of all, see the background map section to understand the basics of mapping with d3, and the most basic choropleth map post.

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

  • Each country is actually a path. Two functions are triggered when the mouse hover/leave the country: mouseOver and mouseLeave

  • Those two functions basically modify the opacity and the stroke of paths.
<!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) {

  let mouseOver = function(d) {
      .style("opacity", .5)
      .style("opacity", 1)
      .style("stroke", "black")

  let mouseLeave = function(d) {
      .style("opacity", .8)
      .style("stroke", "transparent")

  // 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(;
      .style("stroke", "transparent")
      .attr("class", function(d){ return "Country" } )
      .style("opacity", .8)
      .on("mouseover", mouseOver )
      .on("mouseleave", mouseLeave )


Related blocks →

  • World Choropleth - link

  • Projection Transitions - link

  • Choropleth section - link