-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstacked_bar.html
101 lines (92 loc) · 2.9 KB
/
stacked_bar.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3: Bar chart Interactivity</title>
<script type="text/javascript" src="../d3/d3.js"></script>
<style type="text/css">
</style>
</head>
</head>
<body>
<script type="text/javascript">
var w = 500;
var h = 300;
// 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 }
// ];
//This dataset is the above translated to an array of arrays of hashes. Each array is a fruit type
var dataset = [
[
{ x: 0, y: 5 },
{ x: 1, y: 4 },
{ x: 2, y: 2 },
{ x: 3, y: 7 },
{ x: 4, y: 23 }
],
[
{ x: 0, y: 10 },
{ x: 1, y: 12 },
{ x: 2, y: 19 },
{ x: 3, y: 23 },
{ x: 4, y: 17 }
],
[
{ x: 0, y: 22 },
{ x: 1, y: 28 },
{ x: 2, y: 32 },
{ x: 3, y: 35 },
{ x: 4, y: 43 }
]
];
var stack = d3.layout.stack();
//Stacking the dataset
stack(dataset);
//Set up scales
var xScale = d3.scale.ordinal()
.domain(d3.range(dataset[0].length))
.rangeRoundBands([0, w], 0.05);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {
return d3.max(d, function(d) {
return d.y0 + d.y;
});
})
])
.range([0, h]);
var colors = d3.scale.category10();
//Creating the SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Adding a group for each row of data
var groups = svg.selectAll("g")
.data(dataset)
.enter()
.append("g")
.style("fill", function(d, i) {
return colors(i);
});
//adding a rectangle 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.y0);
})
.attr("height", function(d) {
return yScale(d.y);
})
.attr("width", xScale.rangeBand());
</script>
</body>
</html>