Created
May 14, 2013 02:18
-
-
Save anonymous/5573179 to your computer and use it in GitHub Desktop.
Gist from mistakes.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void require('http://d3js.org/d3.v3.min.js'); | |
// An introduction to d3js scales | |
// | |
// scales are transformations from an input | |
// domains to output ranges. you use them for | |
// transforming your input data into your output | |
// representation: $1B in the stock market might | |
// mean 200px on a laptop screen, and so on. | |
// Linear scales are the simplest kind: at most | |
// they divide or multiply their input by a | |
// coefficient. But not necessarily: here's | |
// an identity scale. | |
identityScale = d3.scale.linear() | |
.domain([0, 1]) | |
.range([0, 1]); | |
// 0 goes in, 0 comes out. | |
identityScale(0); | |
// 1 goes in, 1 comes out. | |
identityScale(1); | |
// by default, linear scales don't clamp their input | |
// values: if you provide a value outside of the | |
// domain, it'll scale it just the same | |
identityScale(2); | |
// if you set the scale to clamp, it'll always | |
// output in the output range | |
identityScale.clamp(true)(2); | |
// Here's a more worthwhile linear scale: the | |
// output range is much smaller than the input domain | |
largeScale = d3.scale.linear() | |
.domain([-10000, 100000]) | |
.range([0, 1]); | |
// This scales the output down significantly. | |
largeScale(10); | |
// Scales can also invert values: you give them an output | |
// and they give you the input necessary to get it. | |
pointOnScale = largeScale(1000); | |
// back to the input | |
largeScale.invert(pointOnScale); | |
// While the result of a linear scale is always just | |
// the input multiplied by some number, you might need | |
// a non-linear transformation. For this, you can use | |
// the sqrt scale. | |
sqrtScale = d3.scale.sqrt() | |
.domain([0, 10]) | |
.range([0, 10]); | |
sqrtScale(5); | |
// but that's just shorthand: the pow scale can give | |
// you any exponent: | |
powScale = d3.scale.pow() | |
.exponent(2) | |
.domain([0, 5]) | |
.range([0, 10]); | |
powScale(0.5); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment