forked from jtr13/D3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EDAV6_2_yaxis.html
executable file
·128 lines (91 loc) · 2.75 KB
/
EDAV6_2_yaxis.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>EDAV6_2_yaxis</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<h2>Add y-axis</h2>
<script id="s1">
// Create svg and initial bars
var w = 500;
var h = 400;
var margin = {top: 25, right: 0, bottom: 25,
left: 25};
var innerWidth = w - margin.left - margin.right;
var innerHeight = h - margin.top - margin.bottom;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", w)
.attr("height", h)
.attr("fill", "lightblue");
var bardata = [300, 100, 150, 220, 70, 270];
var xScale = d3.scaleBand()
.domain(d3.range(bardata.length))
.range([0, innerWidth])
.paddingInner(.1);
var yScale = d3.scaleLinear()
.domain([0, d3.max(bardata)])
.range([innerHeight, 0])
var yAxis = d3.axisLeft() // NEW
.scale(yScale);
var bars = svg.append("g")
.attr("id", "plot") // NEW
.attr("transform", `translate (${margin.left}, ${margin.top})`)
.selectAll("rect")
.data(bardata);
bars.enter().append("rect")
.attr("x", (d, i) => xScale(i))
.attr("y", d => yScale(d))
.attr("width", xScale.bandwidth())
.attr("height", d => innerHeight - yScale(d))
.attr("fill", "blue");
svg.append("g") // NEW
.attr("class", "yAxis")
.attr("transform", `translate (${margin.left}, ${margin.top})`)
.call(yAxis);
// General Update Pattern
function update(data) {
xScale.domain(d3.range(data.length));
yScale.domain([0, d3.max(data)]);
var bars = svg.select("#plot")
.selectAll("rect")
.data(data);
bars.enter().append("rect")
.merge(bars)
.attr("x", (d, i) => xScale(i))
.attr("y", d => yScale(d))
.attr("width", xScale.bandwidth())
.attr("height", d => innerHeight - yScale(d))
.attr("fill", "blue");
bars.exit().remove();
svg.select(".yAxis") // NEW
.call(yAxis);
}
</script>
<p id="add">Add an element</p>
<p id="remove_left">Remove bar (left)</p>
<p id="remove_right">Remove bar (right)</p>
<script>
d3.selectAll("p")
.on("click", function () {
var paraID = d3.select(this).attr("id");
if (paraID == "add") {
var newvalue = Math.floor(Math.random()*400);
bardata.push(newvalue);
} else if (paraID == "remove_left") {
bardata.shift();
} else {
bardata.pop();
};
update(bardata);
});
</script>
</body>
</html>