Making Graphs
Scales
Scales are functions that map from an input domain to an output range
Linear Scales
Linear scales have equal division for equal values. We input a svg to grid and scale it down to fit the demensions so it doesn't run off the screen. Consider the following:
const y = d3.scaleLinear()
.domain([0, 828])
.range([0, 400])
console.log(y(100)) // 48.3
console.log(y(828)) // 400
console.log(y(414)) // 200
console.log(y.invert(48.3)) // 100
console.log(y.invert(400)) // 414
console.log(y.invert(200)) // 428
One of the most common types of linear scales is a time scale. The input is a JS Date Object and the output is a number. Keep in mind months are indexed starting at 0.
const x = d3.scaleTime()
.domain([
new Date(2000,0,1),
new Date(2001, 0, 1)
])
.range([0, 400])
console.log(x(new Date(2000, 7, 1)) // 199
console.log(x.invert(199)) // Tue Aug 01 2000
Logaritmic Scales for Diverging Data
Often data sets that grow over time will grow exponentially, such as population. In these cases we would need to use a log scale.
Performing a log scale on a dataset will change the difference between points in a data set to be even (linear).
Remember: You cannot take the log of 0. So never use log on a dataset where the domain passes through 0.
Consider the following:
const y = d3.scaleLog()
.domain([300, 1500000])
.range([0, 400])
.base(10)
console.log(y(500)) // 32.9
console.log(y(5000)) // 181.1
console.log(y(50000)) // 329.3
console.log(y.invert(32.9)) // 500
console.log(y.invert(181.1)) // 5000
console.log(y.invert(329.3)) // 50000
Ordinal Scales
For assigning color schemes to categorical data. If there are more items in the domain than the range then the array loops back around from the start. There are also pre-build color schemes.
const color = d3.scaleOrdinal()
.domain([
"AFRICA", "ASIA"
])
.range([
"RED", "BLUE", "GREEN"
])
console.log("AFRICA") // "RED"
console.log("ASIA") // "BLUE"
console.log("EUROPE") // "GREEN"
console.log("PANGEA") // "RED"