-
Notifications
You must be signed in to change notification settings - Fork 39
/
stacked_bar_transitions.html
280 lines (215 loc) · 7.41 KB
/
stacked_bar_transitions.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
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
<!DOCTYPE html>
<!-- code loosely inspired by this block https://gist.github.com/mstanaland/6100713 -->
<meta charset="utf-8">
<style>
body {
font: 12px sans-serif;
padding: 50px;
}
#form {
position: relative;
right: 10px;
top: 10px;
padding-bottom: 20px;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}
.tooltip {
position: absolute;
z-index: 10;
}
.tooltip p {
background-color: white;
border: gray 1px solid;
padding: 2px;
max-width: 180px;
}
</style>
<body>
<h2>Deaths from Illnesses in 2013 in Selected South African Countries</h2>
<p><a href="http://apps.who.int/gho/data/node.main.ghe100-by-cause?lang=en">WHO data</a>, deaths of children 0-4 years old in selected South African countries.</p>
<div id="form">
<label><input type="radio" name="mode" value="bycount" checked>Raw Count</label>
<label><input type="radio" name="mode" value="bypercent">As Percent of Illness Deaths</label>
</div>
<div id="chart"></div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script>
var currentMode = "bycount";
var fullwidth = 980, fullheight = 500;
var margin = {top: 20, right: 150, bottom: 50, left: 40},
width = fullwidth - margin.left - margin.right,
height = fullheight - margin.top - margin.bottom;
var xScale = d3.scale.ordinal()
.rangeRoundBands([0, width], .3);
var yScale = d3.scale.linear()
.rangeRound([height, 0]);
var color = d3.scale.category20();
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.innerTickSize([0]);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.tickFormat(d3.format(".2s")); // for the stacked totals version
var stack = d3.layout
.stack(); // default view is "zero" for the count display.
var svg = d3.select("#chart").append("svg")
.attr("width", fullwidth)
.attr("height", fullheight)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var tooltip = d3.select("body").append("div").attr("class", "tooltip");
d3.csv("data/deaths_04yearsold_excerpt_2013.csv", function(error, data) {
if (error) {
console.log(error);
}
data.sort(function(a, b) {return d3.ascending(a.Country,b.Country);});
// how would we sort by largest total bar? what would we have to calculate?
var illnesses = ["Meningitis_encephalitis","Respiratory_infections","Sepsis","Pertussis",
"Malaria","Measles","HIV_Aids","Diarrhoeal_diseases","Asphyxia_trauma"];
color.domain(illnesses);
xScale.domain(data.map(function(d) { return d.Country; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.attr("dy", ".5em")
.attr("transform", "rotate(-30)")
.style("text-anchor", "end");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Deaths");
transitionCount(); // this will use the by-count stack, and make the data, and draw.
drawLegend();
d3.selectAll("input").on("change", handleFormClick);
// All the functions for stuff above!
function handleFormClick() {
if (this.value === "bypercent") {
currentMode = "bypercent";
transitionPercent();
} else {
currentMode = "bycount";
transitionCount();
}
}
function makeData(illnesses, data) {
return illnesses.map(function(illness) {
return data.map(function(d) {
return {x: d.Country, y: +d[illness], illness: illness};
})
});
}
function transitionPercent() {
yAxis.tickFormat(d3.format("%"));
stack.offset("expand"); // use this to get it to be relative/normalized!
var stacked = stack(makeData(illnesses, data));
// call function to do the bars, which is same across both formats.
transitionRects(stacked);
}
function transitionCount() {
yAxis.tickFormat(d3.format(".2s")); // for the stacked totals version
stack.offset("zero");
var stacked = stack(makeData(illnesses, data));
transitionRects(stacked);
}
function transitionRects(stacked) {
// this domain is using the last of the stacked arrays, which is the last illness, and getting the max height.
yScale.domain([0, d3.max(stacked[stacked.length-1], function(d) { return d.y0 + d.y; })]);
var illness = svg.selectAll("g.illness")
.data(stacked);
illness.enter().append("g")
.attr("class", "illness")
.style("fill", function(d, i) { return color(d[0].illness); });
// then data for each, plus mouseovers - a nested selection/enter here
illness.selectAll("rect")
.data(function(d) {
console.log("array for a rectangle", d);
return d; }) // this just gets the array for bar segment.
.enter().append("rect")
.attr("width", xScale.rangeBand())
.on("mouseover", mouseover)
.on("mousemove", mousemove)
.on("mouseout", mouseout);
// the thing that needs to transition is the rectangles themselves, not the g parent.
illness.selectAll("rect")
.transition()
.duration(250)
.attr("x", function(d) {
return xScale(d.x); })
.attr("y", function(d) {
return yScale(d.y0 + d.y); }) //
.attr("height", function(d) {
return yScale(d.y0) - yScale(d.y0 + d.y); }); // height is base - tallness
illness.exit().remove(); // there's actually nothing removed here - we just transition.
svg.selectAll(".y.axis").transition().call(yAxis);
}
// Building a legend by hand, based on http://bl.ocks.org/mbostock/3886208
function drawLegend() {
// reverse to get the same order as the bar color layers
var illnesses_reversed = illnesses.slice().reverse();
var legend = svg.selectAll(".legend")
.data(illnesses_reversed) // make sure your labels are in the right order -- if not, use .reverse() here.
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width)
.attr("width", 18)
.attr("height", 18)
.style("fill", function(d) {return color(d)});
legend.append("text")
.attr("x", width + 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "start")
.text(function(d, i) { return illnesses_reversed[i].replace(/_/g, " "); });
}
function mouseover(d) {
// this will highlight both a dot and its line.
var number;
d3.select(this)
.transition()
.style("stroke", "black");
if (currentMode == "bypercent") {
number = d3.format(".1%")(d.y);
} else {
number = d.y;
}
tooltip
.style("display", null) // this removes the display none setting from it
.html("<p>Illness: " + d.illness.replace(/_/g, " ") +
"<br>Deaths: " + number +
"<br>Country: " + d.x + " </p>");
}
function mousemove(d) {
tooltip
.style("top", (d3.event.pageY - 10) + "px" )
.style("left", (d3.event.pageX + 10) + "px");
}
function mouseout(d) {
d3.select(this)
.transition()
.style("stroke", "none");
tooltip.style("display", "none"); // this sets it to invisible!
}
});
</script>