forked from slankas/VisualizationCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.html
More file actions
86 lines (75 loc) · 2.15 KB
/
Copy pathstack.html
File metadata and controls
86 lines (75 loc) · 2.15 KB
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
<!DOCTYPE html>
<!-- https://raw.githubusercontent.com/alignedleft/d3-book/master/chapter_13/05_stacked_bar_anchored.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3: Stack layout stacked bar chart, anchored at bottom</title>
<script src="https://d3js.org/d3.v5.js"></script>
<style type="text/css">
/* No style rules here yet */
</style>
</head>
<body>
<script type="text/javascript">
//Width and height
var w = 500;
var h = 300;
//Original data
var 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
var stack = d3.stack()
.keys([ "apples", "oranges", "grapes" ])
.order(d3.stackOrderDescending); // <-- Flipped stacking order
//Data, stacked
var series = stack(dataset);
//Set up scales
var xScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.range([0, w])
.paddingInner(0.05);
var yScale = d3.scaleLinear()
.domain([0,
d3.max(dataset, function(d) {
return d.apples + d.oranges + d.grapes;
})
])
.range([h, 0]); // <-- Flipped vertical scale
//Easy colors accessible via a 10-step ordinal scale
var colors = d3.scaleOrdinal(d3.schemeCategory10);
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
// Add a group for each row of data
var groups = svg.selectAll("g")
.data(series)
.enter()
.append("g")
.style("fill", function(d, i) {
return colors(i);
});
// Add a rect for each data value
var rects = groups.selectAll("rect")
.data(function(d) { return d; })
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return yScale(d[1]); // <-- Changed y value
})
.attr("height", function(d) {
return yScale(d[0]) - yScale(d[1]); // <-- Changed height value
})
.attr("width", xScale.bandwidth());
</script>
</body>
</html>