# Scales

#### d3_scales.html ● d3.min.js ● data/fruit.csv

### What we wanna do

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.

### Scales

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

### Example

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.

### More scales

Besides the linear transformation we achieved with the scaleLinear() call, D3 also offers further methods to define scales. E.g.:

- scalePow().exponent(exp) Provides a power scale with the given exponent.
- scaleLog() Provides a logarithmic scale with base 10.
- scaleOrdinal() Provides an ordinal scale for which you can provide arrays in the .domain() and .range() method.

There are some additional methods helping you to deal with ordinal scales. One of them you might need is the ordinal.rangeBands(interval) method you can use instead ordinal.range(interval). This method splits the range you pass in into as many sub-intervals of equal length as you have values in your input domain and maps to those interval.

### More about scales

- Scales in the documentation
- List of possible scales