Most basic bubble plot in d3.js

This post describes how to build a very basic bubble plot with d3.js. You can see many other examples in the bubble chart section of the gallery. Learn more about the theory of bubble chart in

Bubbleplot section


  • The Html part of the code just creates a div that will be modified by d3 later on.

  • The first part of the javascript code set a svg area. It specify the chart size and its margin. Read more.

  • Here the gapminder dataset is used, showing the relationship between life expectancy, gdp per capita and population size for more than 100 countries. (.csv format).

  • The building process is basically the same as for a scatterplot. Just add a linear scale for the circle size.
<!DOCTYPE html>
<meta charset="utf-8">

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

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>


// set the dimensions and margins of the graph
var margin = {top: 10, right: 20, bottom: 30, left: 50},
    width = 500 - margin.left - margin.right,
    height = 420 - - margin.bottom;

// append the svg object to the body of the page
var svg ="#my_dataviz")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + + margin.bottom)
          "translate(" + margin.left + "," + + ")");

//Read the data
d3.csv("", function(data) {

  // Add X axis
  var x = d3.scaleLinear()
    .domain([0, 10000])
    .range([ 0, width ]);
    .attr("transform", "translate(0," + height + ")")

  // Add Y axis
  var y = d3.scaleLinear()
    .domain([35, 90])
    .range([ height, 0]);

  // Add a scale for bubble size
  var z = d3.scaleLinear()
    .domain([200000, 1310000000])
    .range([ 1, 40]);

  // Add dots
      .attr("cx", function (d) { return x(d.gdpPercap); } )
      .attr("cy", function (d) { return y(d.lifeExp); } )
      .attr("r", function (d) { return z(d.pop); } )
      .style("fill", "#69b3a2")
      .style("opacity", "0.7")
      .attr("stroke", "black")

Related blocks →