The next thing we want to do is to place the fruits depending on their weight on the x-axis. And we want to use the whole space of the SVG-width.
Last time we worked with static data to create diagrams within which the position and size of visual elements directly corresponded to the data. If we are working with dynamic data, we do not always know the range of values we will receive as input. Hence we cannot encode the position and size of our values in absolute pixel values as we might receive data that exceeds the size of our SVG.
D3 provides scales to solve this problem. They can be used to dynamically scale the visual representation of our data so it always fits into a certain area of our webpage – independent of the value range of our data.
You can think of scales as a function that scales the input domain to an output range. If we know the input domain and output range of our scaling, we can create a scaling function like this:
let maxWeight = 750;
let scaleX = d3.scaleLinear()
.domain([0, maxWeight])
.range([0, 550]);
console.log(scaleX(30)) // Maps 30 to 22 and return 22
Look at the code, we have implemented the scale into out graph and used it to display the fruits on the right place on the x-axis.
Besides the linear transformation we achieved with the scaleLinear() call, D3 also offers further methods to define scales. E.g.: