6 Scales and Axes

6.1 Scales

6.1.1 Lecture slides


6.1.2 Practice

See: IDVW2, Chapter 7: Scales

Practice creating an ordinal scale in the Console:

Open the JavaScript Console

var ordscale = d3.scaleBand()
  .domain([0, 1, 2, 3, 4])
  .range([0, 100]);

Try other numbers: ordscale(3);, ordscale(2.5);, ordscale(7);, etc.

Add inner padding and try again.

See diagram here: https://github.com/d3/d3-scale#band-scales

*Be sure to use d3.scaleBand(), not d3.scaleOrdinal() for this use case.

6.1.3 Examples


IDVW2 Chapter 9, pp. 150-153

Vertical bar chart with labels

d3.scaleBand() used to create an xScale function to convert bar numbers to pixels. Change the w parameter and observe how the bars are resized to fit on the SVG.



Vertical bar chart with labels

d3.scaleLinear() is added to create a yScale function to convert bar heights to pixels. Change the data and observe how the bars are resized to fit on the SVG.


6.2 Margins

6.2.1 Lecture slides


“Margin convention”

  var w = 500;
  var h = 400;
  var margin = {top: 25, right: 0, bottom: 25, left: 25};
  var innerWidth = w - margin.left - margin.right;
  var innerHeight = h - margin.top - margin.bottom;

6.2.2 Example

Full example, vertical bar chart with margins: margins.html

6.3 Axes

See: IDVW2, Chapter 8: Axes

6.3.1 Lecture slides


6.3.2 Example

Full example: vertical bar chart with axes (open in browser): axes.html

To download and open locally: [axes.html] (https://raw.githubusercontent.com/jtr13/d3book/master/code/axes.html){target="_blank"}

Practice changing the data and seeing what happens.