梦入琼楼寒有月,行过石树冻无烟

D3 颜色序数比例尺

作为较为常用且功能逊色的比例尺之一,D3还为其提供颜色序数比例尺,共有四类,10~20种颜色,其方法都以d3.scale.category()来进行定义,他的全部方法共有:

ID DA FA
d3.scale.category10 共有10种颜色
d3.scale.category20 共有20种颜色
d3.scale.category20b 共有20种颜色的第二方案
d3.scale.category20c 第三种共有20种颜色搭配方案

首先我们定义一个高和宽分别为1600的svg图像,之后分别指定圆的颜色为category10,并输出10个圆,圆的边距以及坐标可以通过使用return padding.right + i * padding.left;来计算出坐标以及间隔,并定义一个y轴坐标后输出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var databases = d3.range(10);
var color = d3.scale.category10();

var svg = d3.select("body")
.append("svg")
.attr("width",1600)
.attr("height",1600)

var padding = {
right: 130,
left: 100,
}

var circle = svg.selectAll("circle")
.data(databases)
.enter()
.append("circle")
.attr("cx", function(d,i) {
return padding.right + i * padding.left;
})
.attr("cy",100)
.attr("r",40)
.attr("fill",function (d,i) {
return color(i)
})

/*
/—— font-size and text-anchor
/———— 设置文字大小以及文字居中
/—— return color(i)
/———— 让其生成十个颜色并对应到 text 元素中
/—— text color(d)
/———— 将对应文字输出到 text 中。
*/
var text = svg.selectAll("text")
.data(databases)
.enter()
.append("text")
.attr("font-size","15px")
.attr("text-anchor","middle")
.attr("x",function (d,i) {
return padding.right + i * padding.left;
})
.attr("y",200)
.attr("fill",function (d,i) {
return color(i)
})
.text(function (d) {
return color(d);
})
⬅️ Go back