Tutorials > Intro to D3.js

3. D3.js: Scales

July 9, 2013 | 6 minutes | By Scott Becker

In D3, scales are functions which map data in a dataset to data which makes sense visually. Learn the finer points of quantitative vs ordinal scales, and refactor the bar chart to use d3's scale functions.

 
Watch Preview

 

Resources

Code

Quantitative Linear Scale for Bar Width

var x = d3.scale.linear()
          .domain([0, d3.max(data)])
          .rangeRound([0, width]);

Ordinal Scale for Vertical Position

var y = d3.scale.ordinal()
          .domain(d3.range(0, data.length))
          .rangeBands([0, height]);

Refactored Chart Code

var data = [1.5, 3.5, 5.0, 4.2, 6.7],
    width = 240,
    height = 320,
    padding = 8;

var chart = d3.select('body').append('svg')
  .attr('class', 'chart')
  .attr('width', width)
  .attr('height', height);

var x = d3.scale.linear()
          .domain([0, d3.max(data)])
          .rangeRound([0, width]);

var y = d3.scale.ordinal()
          .domain(d3.range(0, data.length))
          .rangeBands([0, height]);

chart.selectAll('rect').data(data)
    .enter()
  .append('rect')
    .attr('height', y.rangeBand() - padding)
    .attr('width', x)
    .attr('y', function(data, index) { return y(index); });