Scaling D3

Add scales to a d3 plot in three easy steps:

1. Define the scale

1
2
3
4
5
6
7
// 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 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

Apply the scale.link
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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.