scaling d3

March 03, 2014

Add scales to a d3 plot in three easy steps:

1. Define the scale

// Image dimensions
var width = 500,
    height = 500,
    margin = 50;

var scaleX=d3.scale.linear().domain([0,10]).range([margin, width-margin]);
var scaleY=d3.scale.linear().domain([0,10]).range([height-margin, margin]);

2. Draw the scale

// Image container
var svg=d3.select("body").append("svg")
      .attr("width",width)
      .attr("height",height);

// Axis definition
var xAxis = d3.svg.axis()
  .scale(scaleX)
  .orient("bottom");

var yAxis = d3.svg.axis()
  .scale(scaleY)
  .orient("left");

// Axis graphics
svg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(0," + (height - margin) + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(" + margin + ",0)")
  .call(yAxis);

3. Apply the scale to your data

d3.csv("test_data.csv",function(csv) {

  svg.selectAll("circle").data(csv).enter()
    .append("circle")
    .attr("cx",getX)
    .attr("cy",getY)
    .attr("r", getR)
    .style("fill", getColor);

  // Apply scale to the x value
  function getX(d) {
    return scaleX(d.X);
  }

  //Apply scale to the y value
  function getY(d) {
    return scaleY(d.Y);
  }

  function getR(d) {
    return d.Quantity / 10;
  }

  function getColor(d) {
    return d.Colors;
  }
}

Awesome.


Katie Leonard

Mostly Katie explaining things to herself.

© 2025