Basic scatterplot in d3.js

This post describes how to build a very basic scatter plot with d3.js. It is also probably one of the most basic plot you can build in d3. You can visit the scatter plot section for more examples

Scatterplot section


  • The 2 first code chunks are always the same: it defines a svg area with margins. Explanation about it here.

  • The d3.csv() function allows to parse the input dataset that is stored on the web. It has 2 numeric variables called GrLivArea and SalePrice.

  • The X and Y scales and axis are buit using linearScale. Visit this page for more about axis and scales.

  • Lastly, points are added by appending circle to the svg.
<!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: 30, bottom: 30, left: 60},
    width = 460 - margin.left - margin.right,
    height = 400 - - 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, 4000])
    .range([ 0, width ]);
    .attr("transform", "translate(0," + height + ")")

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

  // Add dots
      .attr("cx", function (d) { return x(d.GrLivArea); } )
      .attr("cy", function (d) { return y(d.SalePrice); } )
      .attr("r", 1.5)
      .style("fill", "#69b3a2")



Related blocks →