Drawing a D3.js Scatter Plot

Explains how to draw a basic scatter plot graph in D3.

Example program

View code

Example code

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>D3 Scatter Plot</title>
  <script src="https://d3js.org/d3.v7.min.js"></script>
</head>

<body>
  <script>
  // 1. Prepare data
  var dataset = [
    [5, 20],
    [480, 90],
    [250, 50],
    [100, 33],
    [330, 95],
    [410, 12],
    [475, 44],
    [25, 67],
    [85, 21],
    [220, 88]
  ];

  var width = 400; // Graph width
  var height = 300; // Graph height
  var margin = { "top": 30, "bottom": 60, "right": 30, "left": 60 };

  // 2. Set SVG area
  var svg = d3.select("body").append("svg").attr("width", width).attr("height", height);

  // 3. Set axis scales
  var xScale = d3.scaleLinear()
    .domain([0, d3.max(dataset, function(d) { return d[0]; })])
    .range([margin.left, width - margin.right]);

  var yScale = d3.scaleLinear()
    .domain([0, d3.max(dataset, function(d) { return d[1]; })])
    .range([height - margin.bottom, margin.top]);

  // 4. Display axes
  var axisx = d3.axisBottom(xScale).ticks(5);
  var axisy = d3.axisLeft(yScale).ticks(5);

  svg.append("g")
    .attr("transform", "translate(" + 0 + "," + (height - margin.bottom) + ")")
    .call(axisx)
    .append("text")
    .attr("fill", "black")
    .attr("x", (width - margin.left - margin.right) / 2 + margin.left)
    .attr("y", 35)
    .attr("text-anchor", "middle")
    .attr("font-size", "10pt")
    .attr("font-weight", "bold")
    .text("X Label");

  svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + 0 + ")")
    .call(axisy)
    .append("text")
    .attr("fill", "black")
    .attr("x", -(height - margin.top - margin.bottom) / 2 - margin.top)
    .attr("y", -35)
    .attr("transform", "rotate(-90)")
    .attr("text-anchor", "middle")
    .attr("font-weight", "bold")
    .attr("font-size", "10pt")
    .text("Y Label");

  // 5. Display plots
  svg.append("g")
    .selectAll("circle")
    .data(dataset)
    .enter()
    .append("circle")
    .attr("cx", function(d) { return xScale(d[0]); })
    .attr("cy", function(d) { return yScale(d[1]); })
    .attr("fill", "steelblue")
    .attr("r", 4);
  </script>
</body>

</html>

Example code explanation

The step-by-step scatter plot graph explanation page introduces how to create a scatter plot in detail. This example also adds individual margin settings for the top, bottom, left, and right, plus labels.

1. Prepare data

An object is declared to set margins.

var margin = { "top": 30, "bottom": 60, "right": 30, "left": 60 };

The bottom and left margins are set larger because axes are displayed there.

2. Set SVG area

Set the SVG display area.

3. Set axis scales

Set the axis scales.

d3.scaleLinear()

The code above sets a function that converts the range set with domain(..) to the range set with range(..). It creates functions that convert scatter plot coordinates into screen pixel values.

4. Display axes

Use D3’s d3.axisBottom() and d3.axisLeft() functions to set axis elements. Pass the axis-scale functions as arguments and call them with call, and SVG elements are added automatically.

var axisx = d3.axisBottom(xScale).ticks(5);
var axisy = d3.axisLeft(yScale).ticks(5);

svg.append("g")
  .attr("transform", "translate(" + 0 + "," + (height - margin.bottom) + ")")
  .call(axisx)

svg.append("g")
  .attr("transform", "translate(" + margin.left + "," + 0 + ")")
  .call(axisy)

.ticks() controls the number of tick marks. Set it with an integer.

After calling the axes, add axis labels with text elements.

.append("text")
.attr("fill", "black")
.attr("x", (width - margin.left - margin.right) / 2 + margin.left)
.attr("y", 35)
.attr("text-anchor", "middle")
.attr("font-size", "10pt")
.attr("font-weight", "bold")
.text("X Label");

.append("text")
.attr("fill", "black")
.attr("x", -(height - margin.top - margin.bottom) / 2 - margin.top)
.attr("y", -35)
.attr("transform", "rotate(-90)")
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.attr("font-size", "10pt")
.text("Y Label");

"text-anchor" is an attribute for aligning text positions. Here it is set to "middle" for center alignment. Each label is moved by 35px so it does not overlap the axis.

5. Display plots

Display the plots with circle elements.

svg.append("g")
  .selectAll("circle")
  .data(dataset)
  .enter()
  .append("circle")
  .attr("cx", function(d) { return xScale(d[0]); })
  .attr("cy", function(d) { return yScale(d[1]); })
  .attr("fill", "steelblue")
  .attr("r", 4);

Closing

A scatter plot is one of the most commonly used graphs. The detailed creation method is explained in step-by-step scatter plot graph explanation, so it is helpful to refer to that page as well.