-
Notifications
You must be signed in to change notification settings - Fork 0
/
line-chart with mousemove effect
319 lines (302 loc) · 9.99 KB
/
line-chart with mousemove effect
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
<!DOCTYPE html>
<html>
<head>
<title>D3.js Line_Chart</title>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>
<meta charset="utf-8" />
</head>
<body>
<button onclick="add()">Add data series</button>
<button onclick="remove()">remove data series</button>
<script>
let data = [
{
category: "series_1",
values: [
{ name: "A", value: 10 },
{ name: "B", value: 21 },
{ name: "C", value: 19 },
{ name: "D", value: 23 },
{ name: "E", value: 20 },
{ name: "F", value: 30 },
],
},
];
let data_0 = JSON.parse(JSON.stringify(data[0]));
// function for adding data
let counter = 1;
const add_set = (arr) => {
let copy = JSON.parse(JSON.stringify(arr[0]));
const random = () => Math.floor(Math.random() * 30 + 1);
const add = (arr) => {
counter++;
copy.values.map((i) => (i.value = random()));
copy.category = `series_${counter}`;
arr.push(copy);
};
add(arr);
};
const add = () => {
if (data.length === 0) {
data = [data_0];
setup();
draw(data);
counter++;
} else {
add_set(data);
draw(data);
}
};
// function for removing data
const remove_set = (arr) => {
counter--;
data.pop();
};
const remove = () => {
let svg = d3.select("body").select("svg");
if (data.length === 1) {
remove_set(data);
svg.remove();
} else {
remove_set(data);
draw(data);
}
};
//initial variables
let svg,
graphWidth,
graphHeight,
totalWidth,
totalHeight,
mainGraph,
pathGraph,
text,
legend;
let margin = { top: 60, right: 10, bottom: 30, left: 85 };
let colorScale = d3.scaleOrdinal().range(d3.schemeSet2);
const setup = () => {
//No.1 define svg, this section runs only once
graphWidth = 690;
graphHeight = 420;
totalWidth = graphWidth + margin.left + margin.right;
totalHeight = graphHeight + margin.top + margin.bottom;
svg = d3
.select("body")
.append("svg")
.attr("width", totalWidth)
.attr("height", totalHeight);
//No.2 define mainGraph
mainGraph = svg
.append("g")
.attr(
"transform",
"translate(" + margin.left + "," + margin.top + ")"
);
setupAxes(data);
//No.4 set axises
mainGraph
.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + graphHeight + ")")
.call(d3.axisBottom(xScale));
mainGraph.append("g").attr("class", "y axis").call(d3.axisLeft(yScale));
//pathGroup g
pathGroup = mainGraph
// .selectAll(".pG")
// .data(data) //data is array inside array, draw a line need this kind of data
// .enter()
.append("g")
.attr("class", "pG");
};
let xScale, yScale, categoriesNames, path;
const setupAxes = (arr) => {
//No.3 define axes
categoriesNames = arr[0].values.map((d) => d.name);
xScale = d3
.scalePoint()
.domain(categoriesNames)
.range([0, graphWidth - 126]); // scalepoint make the axis starts with value compared with scaleBand
yScale = d3
.scaleLinear()
.range([graphHeight, 0])
.domain([
d3.min(arr, (i) => d3.min(i.values, (x) => x.value)),
d3.max(arr, (i) => d3.max(i.values, (x) => x.value)),
]); //* If an arrow function is simply returning a single line of code, you can omit the statement brackets and the return keyword
};
setup();
const draw = (data) => {
//update Axes
setupAxes(data);
mainGraph.select(".y.axis").call(d3.axisLeft(yScale));
mainGraph.select(".x.axis").call(d3.axisBottom(xScale));
//No.5 make lines
let lineGenerator = d3
.line()
.x((d) => xScale(d.name))
.y((d) => yScale(d.value))
.curve(d3.curveMonotoneX);
path = pathGroup.selectAll(".path").data(data);
path.exit().remove();
let line = path // need to use a new variable here, otherwise the animation(transition) won't work
.enter()
.append("path")
.merge(path)
.attr("d", (d) => lineGenerator(d.values))
.attrs({ fill: "none", "stroke-width": 3, class: "path" })
.attr("stroke", (d, i) => colorScale(i));
//apply color to each array
const pathLength = line.node().getTotalLength();
const transitionPath = d3.transition().ease(d3.easeSin).duration(1500);
line
.attrs({
"stroke-dashoffset": pathLength * 3,
"stroke-dasharray": pathLength * 3,
})
.transition(transitionPath)
.attr("stroke-dashoffset", 0);
//No. 6 append text
let textData = data.map((d) => {
return {
category: d.category,
value: d.values[d.values.length - 1],
};
});
let text = pathGroup.selectAll(".text").data(textData);
text.exit().remove();
text
.enter()
.append("text")
.attr("class", "text")
.attr(
"transform",
(d) =>
"translate(" +
xScale(d.value.name) +
"," +
yScale(d.value.value) +
")"
)
.attrs({ x: 3, dy: ".35em" })
.text((d) => d.category)
.attr("opacity", 0)
.transition()
.delay(1000)
.attr("opacity", 1);
// //No.7 append mouse move effects
mainGraph.selectAll(".mouseEffects").remove();
let mouseEffects = mainGraph.append("g").attr("class", "mouseEffects");
mouseEffects.append("path").attr("class", "vline").styles({
stroke: "gray",
"stroke-width": "1px",
opacity: 0,
"stroke-dasharray": "3, 3",
});
let lines = document.getElementsByClassName("path");
let perLine = mouseEffects
.selectAll(".perLine")
.data(data)
.enter()
.append("g")
.attr("class", "perLine");
perLine
.append("circle")
.attr("r", 6)
.styles({
stroke: (d, i) => colorScale(i),
fill: (d, i) => colorScale(i),
"stroke-width": "1px",
opacity: 0,
});
perLine.append("text").attr("transform", "translate(9,3)");
mouseEffects
.append("svg:rect")
.attrs({
width: graphWidth - 90,
height: graphHeight,
fill: "none",
"pointer-events": "all",
})
.on("mouseout", () => {
d3.select(".vline").style("opacity", "0");
d3.selectAll(".perLine circle").style("opacity", "0");
d3.selectAll(".perLine text").style("opacity", "0");
})
.on("mouseover", () => {
d3.select(".vline").style("opacity", "1");
d3.selectAll(".perLine circle").style("opacity", "1");
d3.selectAll(".perLine text").style("opacity", "1");
})
.on("mousemove", function (e) {
let mouse = d3.pointer(e);
d3.select(".vline").attr("d", () => {
let d = "M" + mouse[0] + "," + graphHeight;
d += " " + mouse[0] + "," + 0;
return d;
});
d3.selectAll(".perLine").attr("transform", function (d, i) {
let xPos = mouse[0];
let domain = xScale.domain(),
range = xScale.range();
let rangePoints = d3.range(range[0], range[1], xScale.step());
let yPos = domain[d3.bisect(rangePoints, xPos) - 1];
bisect = d3.bisector(function (d) {
return d.name;
}).right;
idx = bisect(d.values, yPos);
var beginning = 0,
end = lines[i].getTotalLength(),
target = null;
while (true) {
target = Math.floor((beginning + end) / 2);
pos = lines[i].getPointAtLength(target);
if (
(target === end || target === beginning) &&
pos.x !== mouse[0]
) {
break;
}
if (pos.x > mouse[0]) end = target;
else if (pos.x < mouse[0]) beginning = target;
else break; //position found
}
d3.select(this)
.select("text")
.text(yScale.invert(pos.y).toFixed(2));
return "translate(" + mouse[0] + "," + pos.y + ")";
});
});
// //No.8 legend
legend = svg.selectAll(".legend").data(data.map((d) => d.category));
legend.exit().remove();
let newLegend = legend
.enter()
.append("g")
.attrs({
class: "legend",
transform: (d, i) => "translate(0," + i * 20 + ")",
})
.style("opacity", "0");
newLegend
.append("rect")
.attrs({ x: totalWidth - 18, y: 6, width: 18, height: 6 })
.styles({
fill: (d, i) => colorScale(i),
opacity: "1",
});
newLegend
.append("text")
.attrs({ x: totalWidth - 24, y: 6, dy: ".35em" })
.style("text-anchor", "end")
.text((d) => d);
newLegend
.transition()
.duration(500)
.delay((d, i) => 300 + 100 * i)
.style("opacity", "1");
};
draw(data);
</script>
</body>
</html>