-
Notifications
You must be signed in to change notification settings - Fork 34
/
update.Rmd
595 lines (419 loc) · 13.8 KB
/
update.Rmd
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# Update, Enter, and Exit <i class="fa fa-refresh"></i>
<script src="https://d3js.org/d3.v7.js"></script>
Read: *IDVW2*, Chapter 9, pp. 178-184; Chapter 12, pp. 231-249
## Lecture slides <i class="fa fa-television"></i>
[D3 Data Bind](https://github.com/jtr13/d3book/blob/main/pdfs/databind.pdf){target="_blank"}
[Jump to data/enter/append](#data-enter-append)
[Jump to general update pattern](#general-update-pattern-with-merge)
## Use exit selection to remove elements <i class="far fa-minus-square"></i>
*a.k.a. more DOM elements than data values*
We'll start with six circles and remove some.
Open [six_blue_circles.html](code/six_blue_circles.html){target="_blank"} in Chrome and open the JavaScript Console.
Let's bind four data values to the six circles:
``` js
d3.select("svg")
.selectAll("circle")
.data([123, 52, 232, 90]);
```
Click the black triangle to view the `_enter`, `_exit`, and `_groups` fields.
We can store the selection in a variable:
``` js
const circ = d3.select("svg")
.selectAll("circle")
.data([123, 52, 232, 90]);
```
Let's look at the exit selection:
``` js
circ.exit();
```
Try this:
``` js
circ.attr("fill", "red");
```
What happened and why?
Now try this:
``` js
circ.exit().attr("fill", "purple");
```
What happened and why?
What do you think this will do? Try it.
``` js
circ.exit().transition().duration(2000).remove();
```
Create a new variable `circ2` and compare it to `circ`:
``` js
const circ2 = d3.selectAll("circle");
circ.data();
circ2.data();
circ.exit();
circ2.exit();
```
What's going on?
## Use enter selection to add elements <i class="far fa-plus-square"></i>
*a.k.a. more data values than DOM elements*
We'll start with [six_blue_circles.html](code/six_blue_circles.html){target="_blank"} in Chrome and add some circles.
First, let's bind new data to the circles:
``` js
const circ = d3.select("svg")
.selectAll("circle")
.data([123, 52, 232, 90, 34, 12, 189, 110]);
```
And look at the enter selection:
``` js
circ.enter();
```
How many placeholders are in the enter selection?
Let's add circles for each of these placeholders:
``` js
circ.enter()
.append("circle")
.attr("cx", "100")
.attr("cy", (d, i) => i * 50 + 25)
.attr("r", "20")
.attr("fill", "blue");
```
Try this:
``` js
circ.transition()
.duration(3000)
.attr("cx", "400");
```
What do you need to do to act on *all* of the circles?
``` js
d3.select("svg")
.selectAll("circle")
.transition()
.duration(2000)
.attr("cy", (d, i) => (i * 50) + 25)
.attr("cx", "200");
```
## Data / enter / append sequence <i class="fa fa-table"></i>
We'll start with nothing--not even an SVG--and add elements with the data / enter / append sequence.
Work in the Console on this page ([help](index.html#this-book-console)).
> <i class="fa fa-hand-o-right"></i> *Open the JavaScript Console* <i class="fa fa-terminal"></i>
The SVG will be added here:
<br>
<div id="dea"></div>
``` js
d3.select("div#dea")
.append("svg")
.attr("width", "400")
.attr("height", "250");
```
Create an array of values:
``` js
const specialdata = [75, 150, 200];
```
Add rectangles:
``` js
d3.select("svg")
.selectAll("rect")
.data(specialdata)
.enter()
.append("rect")
.attr("x", d => d)
.attr("y", d => d)
.attr("width", "50")
.attr("height", "30")
.attr("fill", "pink");
```
### Labels
Note that we can also label the rectangles with the data value:
``` js
d3.select("svg")
.selectAll("text")
.data(specialdata)
.enter()
.append("text")
.attr("x", d => d + 25)
.attr("y", d => d + 25)
.text(d => d)
.attr("fill", "blue")
.attr("text-anchor", "middle");
```
## Exercise <i class="fas fa-dumbbell"></i>: horizontal bar chart
1. Save a copy of [this exercise](https://raw.githubusercontent.com/jtr13/d3book/main/code/bar_chart_exercise.html){target="_blank"} and open it in your text editor.
Create a horizontal bar chart with bar widths equal to the data values stored in `bardata`. Do so by replacing all the "ADD's" with constants or functions and then uncommenting those lines.
``` js
const bardata = [300, 100, 150, 225, 75, 275];
```
It should look like this:
```{r, out.width='50%',echo=FALSE}
knitr::include_graphics("images/barchart.png")
```
[Solution](solutions.html#update-enter-and-exit-horizontal-bar-chart)
## Merge selections <i class="fa fa-code-fork"></i>
We now know how to work separately with the update, enter, and exit selections. Often in practice we wish to do the same thing or almost the same thing with the enter and update selections. That is where `.merge()` comes in. If we merge the update and enter selections we don't have to repeat our code.
Open [six_blue_circles.html](code/six_blue_circles.html){target="_blank"} in Chrome.
Run the following code in the Console:
``` js
const newdata = [123, 52, 232, 90, 34, 12, 189, 110];
const svg = d3.select("svg");
const circ = svg.selectAll("circle")
.data(newdata);
circ.enter() // 2 placeholders
.append("circle") // placeholders -> circles
.attr("cx", "100") // acts on enter selection only
.attr("cy", (d, i) => (i - 5) * 50)
.attr("r", "20")
.attr("fill", "red")
.merge(circ)
.transition()
.duration(2000)
.attr("cx", "200");
```
Note the pattern:
* Create a data array
* Store the svg selection
* Store the data bind in X
```
X.enter()
.append(some shape)
*add attributes* // acts on enter selection only (no transitions!)
.merge(X)
*attributes, other stuff* // acts on enter and update selections
```
*Do not include transitions in a stored selection!*
## Exercise <i class="fas fa-dumbbell"></i>: merge
Open [this bar chart](code/horiz_bar.html){target="_blank"} in Chrome and work in the Console. (You don't have to download it.)
All of your solutions should begin with:
* Creating a data array (ex. `const dataset = [1, 2, 3];`)
* Selecting the `svg` and storing it (`const svg = d3.select("svg");`)
* Binding the data and storing it (ex. `const bars = svg.selectAll("rect").data(dataset));`)
1. Change the data to any six other values and update the lengths of the bars.
1. Bind a new dataset, `newbardata` to the bars, update the bar lengths, and remove any extra bars.
`newbardata = [250, 125, 80, 100];`
1. Bind a new dataset, `reallynewbardata`, to the bars, then add additional bars so each data value has a bar. Make the outline (stroke) of the new bars a different color.
`reallynewbardata = [300, 100, 250, 50, 200, 150, 325, 275];`
1. Use `.merge()` to combine the update and enter selections into one selection and then transition the height of all of the bars to half their current height.
1. Add text labels inside the bars at the right end with the length of the bar in pixels.
[Solution][Update, Enter, and Exit: merge]
## Groups <i class="fa fa-object-group"></i>
Open [six_blue_circles.html](code/six_blue_circles.html){target="_blank"} in Chrome.
Run this code in the Console:
``` js
const specialdata = [100, 250, 300];
const bars =
d3.select("svg")
.selectAll("rect")
.data(specialdata)
.enter()
.append("rect")
.attr("x", d => d)
.attr("y", d => d)
.attr("width", "50")
.attr("height", "30")
.attr("fill", "red");
```
What's going on?
Refresh the page, and try the following instead:
``` js
const svg = d3.select("svg");
const specialdata = [100, 250, 300];
const bars =
d3.select("svg")
.append("g")
.attr("id", "rects")
.selectAll("rect")
.data(specialdata)
.enter()
.append("rect")
.attr("x", d => d)
.attr("y", d => d)
.attr("width", "50")
.attr("height", "30")
.attr("fill", "red");
```
Compare:
``` js
d3.select("svg")
.select("g#rects")
.selectAll("rect")
.attr("fill", "purple");
```
and
``` js
d3.select("svg")
.selectAll("rect")
.attr("fill", "purple");
```
## General Update Pattern (with merge)
Open Developer Tools on this page.
<svg id="gup"></svg>
<script>
d3.select("svg#gup")
.attr("width", "500")
.attr("height", "500");
const bardata = [300, 100, 150, 225, 75, 275];
const bars =
d3.select("svg")
.selectAll("rect")
.data(bardata);
bars.enter()
.append("rect")
.attr("x", "30")
.attr("y", (d, i) => i*50)
.attr("width", d => d)
.attr("height", "35")
.attr("fill", "lightgreen");
</script>
Create a function in the Console:
``` js
function changedata(data) {
d3.select("svg#gup")
.selectAll("rect")
.data(data)
.attr("width", d => d);
}
```
Test it out:
``` js
changedata([258, 373, 278, 9, 72, 96]);
```
What happens if there are too many data values?
``` js
changedata([196, 360, 283, 390, 46, 56, 152]);
```
Let's use the enter selection to add new bars in this case:
``` js
function changedata(data) {
const bars = d3.select("svg#gup")
.selectAll("rect")
.data(data); // bars is the update selection
bars.enter()
.append("rect")
.attr("x", "30") // until merge, acts on
.attr("y", (d, i) => i * 50) // enter selection only
.attr("height", "35")
.attr("fill", "lightgreen")
.merge(bars) // merge in the update selection
.attr("width", d => d); // acts on all bars
}
```
What happens if we have more bars than data values?
``` js
changedata([325, 116, 25]);
```
Let's add to the function to remove the extra bars in this case:
``` js
function changedata(data) {
const bars = d3.select("svg#gup")
.selectAll("rect")
.data(data); // bars is the update selection
bars.enter()
.append("rect")
.attr("x", "30") // until merge, acts on
.attr("y", (d, i) => i * 50) // enter selection only
.attr("height", "35")
.attr("fill", "lightgreen")
.merge(bars) // merge in the update selection
.attr("width", d => d); // acts on all bars
bars.exit()
.remove();
}
```
Try:
``` js
changedata([271, 49, 389]);
```
VOILA! We have created the D3 General Update Pattern!
It is covered in *IDVW* in the "Other Kinds of Data Updates" section on pp. 178-186 in Chapter 9. (The earlier part of Chapter 9 deals with data updates in which the number of DOM elements remains the same.)
**Note that the General Update Pattern changed with D3 Version 4 so avoid examples from Version 3.**
Also available here for download: [general_update_pattern.html](https://raw.githubusercontent.com/jtr13/d3book/main/code/general_update_pattern.html){target="_blank"}
``` js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<script id="s1">
// Create svg and initial bars
const svg = d3.select("body")
.append("svg")
.attr("width", "500")
.attr("height", "400");
const bardata = [300, 100, 150, 225, 75, 275];
const bars = svg.selectAll("rect")
.data(bardata);
bars.enter().append("rect")
.attr("x", "30")
.attr("y", (d, i) => i*50)
.attr("width", d => d)
.attr("height", "35")
.attr("fill", "lightgreen");
// General Update Pattern
function update(data) {
const bars = svg.selectAll("rect") // data join
.data(data);
bars.enter()
.append("rect") // add new elements
.attr("x", "30")
.attr("y", (d, i) => i*50)
.attr("width", d => d)
.attr("height", "35")
.attr("fill", "yellow")
.merge(bars) // merge
.transition()
.duration(2000)
.attr("width", d => d)
.attr("fill", "orange");
bars.exit().remove(); // remove extra elements
}
</script>
</body>
</html>
```
## General Update Pattern (with join)
**Optional**
This is a newer method--introduced in v5--which simplifies the general update pattern by automatically adding elements for the enter selection, removing elements for the exit selection, merging the enter and update selections and then acting on them all with `.join()`.
The update pattern above could be replaced with the following:
```
function changedata2(data) {
const svg = d3.select("svg#gup")
svg.selectAll("rect")
.data(data)
.join("rect") // need "rect" for appending elements
.attr("x", "30")
.attr("y", (d, i) => i * 50)
.attr("height", "35")
.attr("fill", "lightgreen")
.attr("width", d => d);
}
```
Try:
``` js
changedata2([271, 49, 389]);
```
With `.join()` you can get more granular with **enter**, **update**, and **exit** selections as we did previously. `changedata3()` is equivalent to `changedata2()`:
```
function changedata3(data) {
const svg = d3.select("svg#gup")
svg.selectAll("rect")
.data(data)
.join(
enter => enter.append("rect")
.attr("x", "30")
.attr("y", (d, i) => i * 50)
.attr("height", "35")
.attr("width", d => d)
.attr("fill", "lightgreen"),
update => update
.attr("width", d => d),
exit => exit.remove()
);
}
```
Generally, however, unless you have [transitions](transitions.html){target="_blank"}, you will not need to control the enter, exit and update selections separately.
## Exercise: <i class="fas fa-dumbbell"></i>: functions
Open [general_update_pattern.html](code/general_update_pattern.html){target="_blank"} and practice running the `update()` function with different datasets in the Console.
For example:
``` js
update([100, 200, 300]);
```
[Solution][Update, Enter, and Exit: functions]
## Exercise <i class="fas fa-dumbbell"></i>: vertical bar chart
1. Save a copy of [this exercise](https://raw.githubusercontent.com/jtr13/d3book/main/code/bar_chart_exercise.html){target="_blank"} and open it in your text editor.
Create a **vertical** bar chart with bar heights equal to the data values stored in `bardata`. Do so by replacing all the "ADD's" with constants or functions and then uncommenting those lines.
[Solution ][Update, Enter, and Exit: vertical bar chart]