-
Notifications
You must be signed in to change notification settings - Fork 34
/
layouts.Rmd
101 lines (72 loc) · 2.37 KB
/
layouts.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
# Layouts <i class="fa fa-bar-chart"></i>
<script src="https://d3js.org/d3.v7.js"></script>
*IDVW2*, Chapter 13 Layouts (`d3.stack()` only, pp. 264-270)
## Lecture slides <i class="fa fa-television"></i>
[layouts.pdf](pdfs/layouts.pdf){target="_blank"}
## Set up data and stack method
> <i class="fa fa-hand-o-right"></i> *Open the JavaScript Console* <i class="fa fa-terminal"></i>
``` js
// try me in the Console
const w = 500;
const h = 300;
// original data
const dataset = [
{ apples: 5, oranges: 10, grapes: 22 },
{ apples: 4, oranges: 12, grapes: 28 },
{ apples: 2, oranges: 19, grapes: 32 },
{ apples: 7, oranges: 23, grapes: 35 },
{ apples: 23, oranges: 17, grapes: 43 }
];
// set up stack method
const stack = d3.stack()
.keys([ "apples", "oranges", "grapes" ])
.order(d3.stackOrderDescending);
// data, stacked
const series = stack(dataset);
```
Try `stack(dataset)` in the Console.
## Set up scales
``` js
const xScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.range([0, w])
.paddingInner(0.05);
const yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, d => d.apples + d.oranges + d.grapes)])
.range([h, 0]);
const colors = d3.scaleOrdinal(d3.schemeCategory10);
```
Enter `d3.schemeCategory10` in the Console.
Now try out the `colors` function. What is the domain?
See built-in color options [here](https://github.com/d3/d3-scale-chromatic){target="_blank"}. Of course you are not limited to these and can use any appropriate color scheme.
## Add groups
``` js
//Create SVG element
const svg = d3.select("#stacked")
.append("svg")
.attr("width", w)
.attr("height", h);
// Add a group for each row of data
const groups = svg.selectAll("g")
.data(series)
.enter()
.append("g")
.style("fill", (d, i) => colors(i));
```
<div id="stacked"></div>
[There's a div with id "stacked" here.]
Why doesn't anything show up yet? Right-click and Inspect to find out.
## Add rectangles
``` js
// Add a rect for each data value
const rects = groups.selectAll("rect")
.data(d => d)
.enter()
.append("rect")
.attr("x", (d, i) => xScale(i))
.attr("y", d => yScale(d[1]))
.attr("height", d => yScale(d[0]) - yScale(d[1]))
.attr("width", xScale.bandwidth());
```
## Get the code
[Code for download](https://raw.githubusercontent.com/jtr13/d3book/main/code/stackedbar.html){target="_blank"}