d3.js Coordinate System


In a normal mathematical coordinate system, the point x=0, y=0 is at the lower left corner of the graph. But in the SVG coordinate system, this (0,0) point is at the top left corner of the ‘canvas’, it is sort of similar to CSS when you specify the position to absolute/fix and use top and left to control the exact point of the element.

It is essential to keep in mind that as y increases in SVG, the shapes move down.

Let’s say we’re going to create a scatterplot with each point correspondent to a x value and y value. To scale the value, we need to set the domain and the range like this:

  .range([0, height])

However, if you just keep the settings like this, the points will be based on the top horizontal edge instead of the bottom horizontal line as what we expected.

The nice thing about d3 is that you can easily change this by a simple adjustment in domain setting:

  .range([height, 0])
  .domain([0, max])

With above code, the zero point of domain is correspondent to the height of the SVG, which is the bottom line of the chart in the viewer’s eyes, meanwhile, the max value of the source data will be correspondent to the zero point of the SVG coordinate system, which the max value for viewers.