-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter07.html
77 lines (65 loc) · 2.07 KB
/
chapter07.html
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>D3 Chapter 07 比例尺</title>
<script src="d3/d3.min.js"></script>
</head>
<body>
<script type="application/javascript">
let scale = d3.scaleLinear();
// 比例尺的输入值域
scale.domain([100, 500]);
// 比例尺的输出范围
scale.range([10, 350]);
// 将输入值域映射到输出范伟的过程,称为归一化。
console.log(scale(100));
console.log(scale(200));
console.log(scale(300));
const dataset = [
[5, 20], [480, 90], [250, 50], [100, 33], [330, 95],
[410, 12], [475, 44], [25, 67], [85, 21], [220, 88],
[600, 150]
];
const w = 500, h = 300;
// 边距(还不完善)
// 阅读文档:《外边距约定》https://observablehq.com/@d3/margin-convention
const padding = 20;
let svg = d3.select('body')
.append('svg')
.attr('width', w)
.attr('height', h);
// 横向比例尺
let xScale = d3.scaleLinear()
.domain([0, d3.max(dataset, d => d[0])])
// 右侧多留一倍边距防止文字超出画布
.range([padding, w - padding * 2]);
// 纵向比例尺
let yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, d => d[1])])
.range([h - padding, padding]);
// 圆点半径比例尺,作用是将圆点的半径控制在合适的范围内
let rScale = d3.scaleLinear()
.domain([0, d3.max(dataset, d => d[1])])
.range([2, 5]);
let circles = svg.selectAll('circle')
.data(dataset)
.enter()
.append('circle');
circles
.attr('cx', d => xScale(d[0]))
.attr('cy', d => yScale(d[1]))
.attr('r', d => rScale(d[1]));
let texts = svg.selectAll('text')
.data(dataset)
.enter()
.append('text')
.text(d => d[0] + ',' + d[1])
.attr('x', d => xScale(d[0]))
.attr('y', d => yScale(d[1]))
.attr('font-family', "sans-serif")
.attr('font-size', '11px')
.attr('fill', 'red')
</script>
</body>
</html>