Update X axis limits on scatterplot

This post describes how to update the X axis limit with a smooth transition. When the button on top of the scatter plot is updated, both the axis and circles position are smoothly updated. See more on scatter plot, animation and buttons if needed.

Scatterplot section


  • First of all, you need to know how to build a basic scatter plot.

  • Then, add a button on top of it. You can read more about buttons here.

  • The scatterplot is initialized, and a function updatePlot() is created. This function rebuilds the plot if needed for a specific X axis limit.

  • Lastly, a listener to the button is set up: whenever the button value changes, the function updatePlot() is triggered and update the chart.
<!DOCTYPE html>
<meta charset="utf-8">

<!-- Add a radio button -->
<input type="number" id="buttonXlim" value=9>

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></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.top - margin.bottom;

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

//Read the data
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/iris.csv", function(data) {

  // Add X axis
  var x = d3.scaleLinear()
    .domain([3, 9])
    .range([ 0, width ]);
  var xAxis = svg.append("g")
    .attr("transform", "translate(0," + height + ")")

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

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

  // A function that update the plot for a given xlim value
  function updatePlot() {

    // Get the value of the button
    xlim = this.value

    // Update X axis

    // Update chart
       .attr("cx", function (d) { return x(d.Sepal_Length); } )
       .attr("cy", function (d) { return y(d.Petal_Length); } )

  // Add an event listener to the button created in the html part
  d3.select("#buttonXlim").on("input", updatePlot )



Related blocks →