D3.js provides usefull functions for scaling charts. There are many possibilities,
but here, we'll start with the basic. The basic concept is to map a given range
of data to antother. For example [0 10 ] => [0 300]
. In this example,
Let's create a fonction that convert our set of data indexes into x-coordinates:
var xScale = d3.scaleLinear()
.domain([0, dataset.length])
.range([0, width]);
scaleLinear()
specify the mapping will be linear
domain([0, dataset.length])
is used to set the initial domain range, from 0 to the length of dataset
range([0, width])
specify the target range, the width of our chart.
xScale()
is a function that can be called to resize the x-coordinates of our chart:
bars.selectAll('rect')
.data(dataset)
.enter()
.append('rect')
.attr('x', (d,i) => xScale(i) )
.attr('y', (d) => height-d)
.attr('width', xScale(0.9))
.attr('height', (d) => d);
The chart is now expanded to the SVG conteneur width:
Of course, we can do the same here to resize the height of each bar. But we'll use a
slightly different solution. We'll adapt the height of our bars to fit the chart height.
In other words, the tallest bar, will be size to fit the chart height. Here is the
source code for creating the yScale
function:
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset)])
.range([0, height]);
The d3.max(array)
function returns the value of the biggest element in the array.
We can now update the Y properties of our chart:
bars.selectAll('rect')
.data(dataset)
.enter()
.append('rect')
.attr('x', (d,i) => xScale(i) )
.attr('y', (d) => height-yScale(d))
.attr('width', xScale(0.9))
.attr('height', (d) => yScale(d));
The chart has been scaled for the biggest bar (the biggest one) to be the same height as our SVG container.