-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path018_scatter_plot_with_min_max.html
More file actions
90 lines (81 loc) · 2.79 KB
/
018_scatter_plot_with_min_max.html
File metadata and controls
90 lines (81 loc) · 2.79 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
<!DOCTYPE html>
<html>
<head>
<!-- load the d3 v4 javascript library -->
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<!-- d3 script -->
<script>
// define the static data-set
var dataset = [
[5, 20], [480, 90], [250, 50], [100, 33], [330, 95],
[410, 12], [475, 44], [25, 67], [85, 21], [220, 88],
[600, 150] // add an extra data-point to prove the chart auto-scales
];
// define the svg element attributes
var w = 500;
var h = 200;
var xPadding = 40; // left and right svg padding
var yPadding = 20; // top and bottom svg padding
// create an 'x' dynamic scale
var xScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function(d) { return d[0]; })])
.range([xPadding, w - xPadding]);
// .nice() - rounds the min / max range of input domain
// .rangeRound() - use instead of 'range' to round all output range values
// .clamp() - prevents returning output 'range' values outside the given 'range'
// create a 'y' dynamic scale
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function(d) { return d[1]; })])
// reverse the output y pixel range so that the y values
// grow from bottom-to-top (since d3's origin is top-left)
.range([h - yPadding, yPadding]);
// create a circle radius scale
var rScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function(d) { return d[1]; })])
.range([5, 15]);
// create the svg element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
// create each svg circle and set the attributes
svg.selectAll("circle") // select all svg circles
.data(dataset) // bind the data
.enter() // on 'enter' (called for each new data item)
.append("circle") // create the new circle
.attr("cx", function(d, i) {
// scale and set the circle's x position
return xScale(d[0]);
})
.attr("cy", function(d, i) {
// scale and set the circle's y position
return yScale(d[1]);
})
.attr("r", function(d) {
// scale and set the circle's radius
return rScale(d[1]);
});
// create labels
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d, i) {
return d[0] + ", " + d[1];
})
.attr("x", function(d) {
// scale and set the text label's x position
return xScale(d[0]);
})
.attr("y", function(d) {
// scale and set the text label's y position
return yScale(d[1]);
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "red");
</script>
</body>
</html>