六、d3比例尺

212 阅读1分钟

为什么需要比例尺

绘制图表时依赖的数据,可能太大,也可能太小,而要将太大或太小的数据,绘制在一个画布中,那就需要对原始数据进行一定的转换,这个转换的工具就是比例尺。

d3常用比例尺

线性比例尺

定义

能将一个连续的区间,映射到另一区间。

使用示例

将 dataset 中最小的值,映射成 0;将最大的值,映射成 300。

var dataset = [1.2, 2.3, 0.9, 1.5, 3.3];
import { scaleLinear } from 'd3-scale'
import { min, max } from 'd3-array'

const dataset = [1.2, 2.3, 0.9, 1.5, 3.3]
const minVal = min(dataset) as number
const maxVal = max(dataset) as number

// domain()用来指定义域,range()用来指定值域。
const linear = scaleLinear().domain([minVal, maxVal]).range([0, 300])

console.log(linear(0.9)) //返回 0
console.log(linear(2.3)) //返回 175
console.log(linear(3.3)) //返回 300

序数比例尺

定义

定义域和值域不一定是连续的。要让他们一一映射则需要序数比例尺。

使用示例

将如下的数字和颜色建立映射关系

var index = [0, 1, 2, 3, 4];
var color = ["red", "blue", "green", "yellow", "black"];
import { scaleOrdinal } from 'd3-scale'

const index = [0, 1, 2, 3, 4]
const color = ['red', 'blue', 'green', 'yellow', 'black']

//@ts-ignore
const ordinal = scaleOrdinal().domain(index).range(color)

//@ts-ignore
console.log(ordinal(0)) //返回 red
//@ts-ignore
console.log(ordinal(2)) //返回 green
//@ts-ignore
console.log(ordinal(4)) //返回 black

序数比例尺

定义

使用示例

参考文章

d3.js 入门学习记录(四) 尺度scale的使用

D3入门教程——比例尺的使用

d3常用比例尺总结

D3比例尺与坐标轴

D3.js scale比例尺介绍

D3 比例尺小记

D3基础03 - 比例尺与坐标轴