-
Notifications
You must be signed in to change notification settings - Fork 34
/
console.Rmd
447 lines (286 loc) · 12.6 KB
/
console.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
# Modify, Add, Remove <i class="fa-solid fa-shapes"></i> {#d3console}
Read *IDVW2*, Chapter 6: Drawing with Data. Skip pp. 89-96 as we will not be drawing bar charts with the `div`approach.
<script src="https://d3js.org/d3.v7.js"></script>
## Selections <i class="fas fa-clipboard-list"></i>
### Select by tag
The ability to select elements on a page is key to being able to manipulate them. `d3.select()` will select the first match; `d3.selectAll()` will select all matches.
``` js
d3.select("svg").select("circle");
```
selects the first circle in the order in which circles appear in the `<svg>` grouping. If there were more than one circle we could select them all with:
``` js
d3.select("svg").selectAll("circle");
```
We can select HTML elements by tag in the same way:
``` js
d3.select("body").select("h1");
d3.select("body").selectAll("h1");
```
### Select by class
Classes are selected by adding a "." before the class name:
``` js
d3.select("svg").selectAll("circle.apple")
```
This provides one method of selecting a certain collection of elements of the same type.
### Select by ID
IDs differ from classes in that they are unique identifiers. IDs are selected by adding a "#" before the ID:
``` js
d3.select("svg").select("circle#henry");
```
### Store selections
It is often helpful to store selections for later use. Here we store the svg selection in `mysvg`:
``` js
const mysvg = d3.select("svg");
```
> <i class="far fa-lightbulb"></i> *The JavaScript community is moving toward using `let` and `const` instead of `var`; we, however, will stick with `var` to be consistent with *IDVW2*. Of course you're welcome to use `const` and `let` instead, and if so, may find these articles helpful: [Let It Be - How to declare JavaScript variables](https://madhatted.com/2016/1/25/let-it-be){target="_blank"} and [ES2015 const is not about immutability](https://mathiasbynens.be/notes/es6-const){target="_blank"}.*
Store circle selection in a variable:
``` js
const svg = d3.select("svg");
const circ = svg.selectAll("circle");
```
## Modify existing elements <i class="fas fa-exchange-alt"></i>
Try out the code in this section with a downloaded copy of [five_green_circles.html](https://raw.githubusercontent.com/jtr13/d3book/main/code/five_green_circles.html){target="_blank"} opened in Chrome and the Console visible.
### Modify attributes
[link to get or set attribute API](https://github.com/d3/d3-selection/blob/v1.4.0/README.md#selection_attr)
``` js
d3.select("circle").attr("r"); // see radius
d3.select("circle").attr("r", "10"); // set radius to 10
```
### Modify styles
[link to get or set style API](https://github.com/d3/d3-selection/blob/v1.4.0/README.md#selection_style)
``` js
d3.select("h1").style("color");
d3.select("h1").style("color", "blue");
```
> <i class="far fa-lightbulb"></i> *It is often difficult to remember whether to use `.attr()` or `.style()` In general, properties such as position on the SVG, class, and ID are *attributes*, while decorative properties such as color, font, font size, etc. are *styles*. However, in some cases, you can use either. For example, the following both make the circle blue:*
``` js
d3.select("circle").attr("fill", "blue");
d3.select("circle").style("fill", "blue");
```
*The first will add a `fill="blue"` attribute to the `<circle>` tag, while the latter will add `style="fill: blue;"`. All is well and good until you find yourself with both in the same tag, in which case the `style` property will take precedence. The bottom line: don't mix the two options because it can cause problems.*
> <i class="far fa-lightbulb"></i> *To further complicate matters, `.style()` is just shorthand for `.attr("style", "...")` so the following are in fact equivalent:*
``` js
d3.select("circle").style("fill", "blue");
d3.select("circle").attr("style", "fill: blue;");
```
*In other words, style is an attribute!* <i class="far fa-grimace"></i>
### Modify text
This section is interactive: You can hover over code as directed to observe effects.
The interactivity is enabled by D3 scripts that are included in the `.Rmd` source file of this page. If you're interested you can view these scripts by either clicking on the eye icon above <i class="fa fa-eye"></i> or opening Developer Tools in Chrome. In either case, look for the code between the `<script>` `</script>` tags.
#### HTML text {-}
<style>
.fancy {
color: red;
font-family: garamond;
font-size: 30px;
}
</style>
``` html
<p id="typo" class="fancy">Manhatten</p>
```
<div>
<p id="typo" class="fancy">Manhatten</p>
</div>
Hover to execute this code (and fix the typo):
<div id="fixtypo">
```{js, eval=FALSE}
d3.select("#typo").text("Manhattan");
```
</div>
<script>
d3.select("#fixtypo")
.on("mouseover", function () {
d3.select("#typo").text("Manhattan")
})
.on("mouseout", function () {
d3.select("#typo").text("Manhatten")
});
</script>
#### SVG text {-}
``` svg
<svg width="500" height="100">
<rect width="500" height="100" fill="#326EA4"></rect>
<text id="svgtypo" x="50" y="70" fill="white" font-weight="bold" font-size="40px">
Web scrapping is fun.</text>
</svg>
```
Hover on this SVG to execute the code below it (and fix the typo):
<svg width="500" height="100">
<rect width="500" height="100" fill="#326EA4"></rect>
<text id="svgtypo" x="50" y="70" fill="white"
font-weight="bold" font-size="40px">
Web scrapping is fun.</text>
</svg>
<div id="fixsvgtypo">
```{js, eval=FALSE}
d3.select("#svgtypo").text("Web scraping is fun.");
```
</div>
<script>
d3.select("#fixsvgtypo")
.on("mouseover", function () {
d3.select("#svgtypo").text("Web scraping is fun.")
})
.on("mouseout", function () {
d3.select("#svgtypo").text("Web scrapping is fun.")
});
</script>
> <i class="far fa-lightbulb"></i> *The SVG `<text>` tag can be tricky. It differs from HTML text tags (`<p>, <h1>, <h2>,` etc.) in that it has `x` and `y` attributes that allow you to position text on an SVG canvas. Unlike HTML, the fill attribute controls the color of the text. Compare:*
``` js
d3.select("p").style("color", "red"); // HTML
d3.select("text").attr("fill", "red"); // SVG
```
### Move SVG text
``` svg
<svg width="600" height="100">
<rect width="600" height="100" fill="#326EA4"></rect>
<text id="moveleft" x="200" y="70" fill="white" font-weight="bold" font-size="40px">
I want to move left.</text>
</svg>
```
Hover on this SVG to execute the code below it:
<svg width="600" height="100">
<rect width="600" height="100" fill= "#326EA4"></rect>
<text id="moveleft" x="200" y="70" fill="white"
font-weight="bold" font-size="40px">I want to move left.</text>
</svg>
<div id="move">
```{js, eval=FALSE}
d3.select("#moveleft").attr("x", "20").text("Thanks, now I'm happy!");
```
</div>
<script>
d3.select("#move")
.on("mouseover", function () {
d3.select("#moveleft").attr("x", "20").text("Thanks, now I'm happy!")
})
.on("mouseout", function () {
d3.select("#moveleft").attr("x", "200").text("I want to move left.")
});
</script>
## Add elements <i class="far fa-plus-square"></i>
### HTML
Continue trying out code with [five_green_circles.html](code/five_green_circles.html){target="_blank"} open in Chrome.
Or [download the file](https://raw.githubusercontent.com/jtr13/d3book/main/code/five_green_circles.html){target="_blank"} and open it.
The following adds a `<p>` tag but doesn't change how the page looks, since there's no text associated with it.
``` js
d3.select("body").append("p");
```
To add text, use `.text()`:
``` js
d3.select("body").append("p").text("This is a complete sentence.");
```
> <i class="far fa-lightbulb"></i> *To debug adding an element, go to the Elements tab to see what was added and where. If an element is in the wrong place in the HTML tree, it will not be visible.*
### SVG
Likewise, here we add a `<circle>` to the `<svg>`, but we can't see it since it has no attributes.
``` js
d3.select("svg").append("circle");
```
Adding attributes will create visible circles:
``` js
d3.select("svg").append("rect").attr("x", "0").attr("y", "0")
.attr("width", "500").attr("height", "400").attr("fill", "lightblue");
d3.select("svg").append("circle").attr("cx", "200")
.attr("cy", "100").attr("r", "25").attr("fill", "orange");
d3.select("svg").append("circle").attr("cx", "300")
.attr("cy", "150").attr("r", "25").attr("fill", "red");
```
We can use a saved selection to assist in creating a new element:
(*IDVW2*, pp. 97-98)
``` js
mysvg = d3.select("svg");
mysvg.append("circle").attr("cx", "250").attr("cy", "250").attr("r", "50")
.attr("fill", "red");
```
## Remove elements <i class="far fa-minus-square"></i>
These methods will remove matching elements in order, starting with the first find in the document.
### HTML
``` js
d3.select("p").remove();
```
### SVG
``` js
d3.select("svg").select("circle").remove();
d3.select("svg").selectAll("circle").remove();
```
## Exercise <i class="fas fa-dumbbell"></i>: green circles
Return to [five_green_circles.html](code/five_green_circles.html){target="_blank"}, open Developer Tools, and do the following in the Console with D3:
1. Select the circle with ID "henry" and make it blue.
2. Select all circles of "apple" class make them red.
3. Select the first circle and add an orange border (use attribute "stroke"), and stroke width ("stroke-width") of 5.
4. Select all circles of "apple" class and move them to the middle of the svg.
[Solution](solutions.html#d3-in-the-console-green-circles)
## Exercise <i class="fas fa-dumbbell"></i> <i class="fas fa-dumbbell"></i>: blue circles
Return to [six_blue_circles.html](code/six_blue_circles.html){target="_blank"}, open Developer Tools, and execute Steps 1-4 one at a time in the Console. After Step 4, refresh the page to go back to Step 1 if so desired. (You do not need to create a loop as in the visual.)
> <i class="far fa-lightbulb"></i> *This exercise is provided as a challenge. It's fine to skip this exercise and move on to the next section.*
<table>
<col width="50%">
<col width="50%">
<tr><td>
1. Move all the circles to the right.
2. Move them back to the left *and* change their color.
3. In a text editor, add an id to the third circle in `six_blue_circles.html`, save the file, and then in the Console, move only that circle to the right.
4. Move all the circles to the middle of the screen, *then* move them all to the same location.
</td><td>
<svg id="jump1" width="500" height="400"></svg>
<script src="scripts/jump1.js"></script>
</td></tr></table>
[Solution](solutions.html#d3-in-the-console-blue-circles)
## Bind data… *finally\!* <i class="fas fa-table"></i>
(*IDVW2*, pp. 98-108)
To follow along with the code in this section, download and open [six_blue_circles.html](https://raw.githubusercontent.com/jtr13/d3book/main/code/six_blue_circles.html){target="_blank"}.
Bind data:
``` js
d3.select("svg").selectAll("circle").data([90, 230, 140, 75, 180, 25]);
```
Check data binding:
``` js
d3.select("svg").selectAll("circle").data();
```
Set x-coordinate of each circle to data value using arrow function:
``` js
d3.select("svg").selectAll("circle").attr("cx", d => d);
```
Set x-coordinate of each circle to data value with a JavaScript function:
``` js
d3.select("svg").selectAll("circle").attr("cx", function(d) {return d;});
```
We'll bind a new set of data to the circles, this time storing the dataset in a variable:
``` js
const dataset = [50, 80, 110, 140, 170, 200];
```
We'll also store a selection of all circles before binding the data:
``` js
const circ = d3.select("svg").selectAll("circle");
```
And now, the data bind:
``` js
circ.data(dataset);
```
Nothing appears to have happened; the circles remain the same and there is no evidence of any changes looking at the circles in the DOM (see Elements tab).
We can check that the data are indeed bound with:
``` js
circ.data(); // now we see data
```
Modify elements w/ stored selections, bound data:
``` js
circ.attr("cx", function(d) {return d;});
circ.attr("cx", function(d) {return d/2;});
circ.attr("cx", function(d) {return d/4;}).attr("r", "10");
```
Same as above, using arrow functions:
``` js
circ.attr("cx", d => d);
circ.attr("cx", d => d/2);
circ.attr("cx", d => d/4).attr("r", "10");
```
Note that if we bind a new set of data to the DOM elements, the original set will be overwritten:
``` js
const newdata = [145, 29, 53, 196, 200, 12];
circ.data(newdata);
circ.transition()
.duration(2000)
.attr("cx", d => 2*d);
```
## Exercise <i class="fas fa-dumbbell"></i>: data bind
Return to [six_blue_circles.html](code/six_blue_circles.html){target="_blank"}, open Developer Tools, and practice binding data to the circles and modifying the circles based on the data as in the examples above.