-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbarchart.html
361 lines (309 loc) · 9.78 KB
/
barchart.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
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
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<!-- Load d3-annotation -->
<script src="https://rawgit.com/susielu/d3-annotation/master/d3-annotation.min.js"></script>
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}
</style>
<button onclick="update('grouped')">Grouped</button>
<button onclick="update('stacked')">Stacked</button>
<!-- Create a div where the graph will take place -->
<div id="barchart"></div>
<script>
// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// create two x and y axis for each barchart
var x0 = d3.scaleBand().range([0, width]);
var x1 = d3.scaleBand();
var y = d3.scaleLinear()
.range([height, 0]);
var y1 = d3.scaleLinear()
.range([height, 0]);
var xAxis = d3.axisBottom()
.scale(x0);
var yAxis = d3.axisLeft()
.scale(y)
.tickFormat(d3.format(".2s"));
var y1Axis = d3.axisLeft()
.scale(y1)
.tickFormat(d3.format(".2s"));
var color = d3.scaleOrdinal().range(
["#fbb4ae", "#b3cde3"]);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var yBegin;
var innerColumns = {
"column1" : ["pass"],
"column2" : ["fail"],
}
// A function that creates / updates the plot depending on the selection
function update(chart_type){
// remove previous elements on chart switch
svg.selectAll('rect').remove()
svg.selectAll('tspan').remove()
svg.selectAll('g.y.axis').remove()
svg.selectAll('g.x.axis').remove()
d3.selectAll('g.tooltip').remove()
d3.selectAll('circle.annotation').remove()
// create annotations
text = svg.append('text')
.attr("y", 100)
.attr("x", 100)
.style("text-anchor", "left")
.style("font-size","12px")
text
.append("tspan")
.text("Digging into the data further, we can see that")
.append("tspan")
.attr("dy", "1em")
.attr("x", 100)
.text("although more movies pass the Bechdel Test over time,")
.append("tspan")
.attr("dy", "1em")
.attr("x", 100)
.text("proportionally still more fail.")
.append("tspan")
.attr("dy", "2em")
.attr("x", 100)
.text("Hover over the bars for more information.")
;
// read in the data from csv
d3.csv("data/barchart.csv").then(
function(data) {
// year will be displayed on the x axis, so exclude it
var columnHeaders = d3.keys(data[0]).filter(function(key) { return key !== "year"; });
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "year"; }));
data.forEach(function(d) {
var yColumn = new Array();
d.columnDetails = columnHeaders.map(function(name) {
for (ic in innerColumns) {
if($.inArray(name, innerColumns[ic]) >= 0){
if (!yColumn[ic]){
yColumn[ic] = 0;
}
yBegin = yColumn[ic];
yColumn[ic] += +d[name];
return {name: name, column: ic, yBegin: yBegin, yEnd: +d[name] + yBegin,};
}
}
});
d.total = d3.max(d.columnDetails, function(d) {
return d.yEnd;
});
});
// create stacked data
var stackedData = d3.stack()
.keys(['pass','fail'])
(data);
// assign data domains
x0.domain(data.map(function(d) { return d.year; }));
x1.domain(d3.keys(innerColumns)).range([0, x0.bandwidth()]).padding([0.05]);
y.domain([0, d3.max(data, function(d) {
return d.total; })]);
y1.domain([0,160]);
// create labels for x axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.attr("y", -4)
.attr("transform", "rotate(-90)")
.attr("dx", "-0.8em")
.style("text-anchor", "end");
// create subgroups for grouped barchart
var subgroups = data.columns.slice(1)
var xSubgroup = d3.scaleBand()
.domain(subgroups)
.range([0, x0.bandwidth()])
.padding([0.05])
// add tooltip
var tooltip = d3.select("body")
.append("g")
.style("opacity", 0)
.attr("class", "tooltip")
.style("background-color", "white")
.style("border", "solid")
.style("border-width", "1px")
.style("left", "70px")
.style("top", "40px")
.style("position", "absolute")
.style("width", "40px")
.style("border-radius", "5px")
.style("padding", "10px")
.style("opacity", 0)
// What happens when the user hovers over a bar
var mouseover = function(d) {
if (chart_type == 'stacked'){
var subgroupName = d3.select(this.parentNode).datum().key;
var subgroupValue = d.data[subgroupName];
}
else{
var subgroupName = d3.select(this).datum().key
var subgroupValue = d.value;
}
// Reduce opacity of all rect to 0.2
d3.selectAll("myRect").style("opacity", 0.2)
// Highlight all rects of this subgroup with opacity 0.8. It is possible to select them since they have a specific class = their name.
d3.selectAll("."+subgroupName + subgroupValue).style("opacity", 1)
tooltip
.html(subgroupName + "<br>" + "Count: " + subgroupValue)
.style("opacity", 1)
}
// When user moves over a bar
var mousemove = function(d) {
tooltip
.style("left", (d3.mouse(this)[0]+90) + "px")
.style("top", (d3.mouse(this)[1]) + "px")
}
// When user does not hover anymore
var mouseleave = function(d) {
// Back to normal opacity: 0.8
d3.selectAll(".myRect")
.style("opacity",0.8)
}
if (chart_type == 'grouped'){
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".7em")
.style("text-anchor", "end")
.text("");
// create grouped barchart div
var grouped_barchart = svg.selectAll(".grouped_barchart")
.data(data)
.enter().append("g")
.attr("transform", function(d) { return "translate(" + x0(d.year) + ",0)"; })
.selectAll("rect")
.data(function(d){ return subgroups.map(function(key){return {key:key, value: d[key]};});})
.enter().append("rect")
.attr("class", function(d,i){return "myRect " + d.key + d.value}) // Add a class to each subgroup
// add transition as well as height and fill
grouped_barchart.attr("y", 500)
.transition()
.delay(function(d,i){return d.value * 10})
.attr("width", x1.bandwidth())
.attr("x", function(d) { return xSubgroup(d.key); })
.attr("y", function(d) {
return y(d.value);
})
.attr("height", function(d) {
return height - y(d.value);
})
.style("fill", function(d) {
return color(d.key);
})
// add tooltip and highlighting functionality
grouped_barchart.on("mouseover", mouseover)
.on('before:mousemove', function (coordinates) {
var target = instance.root.node().parentNode;
scaleX = target.offsetWidth / target.getBoundingClientRect().width;
scaleY = target.offsetHeight / target.getBoundingClientRect().height;})
.on("mouseleave", mouseleave)
// add annotation
text = svg.append('text')
.attr("y", 120)
.attr("x", 700)
.style("text-anchor", "middle")
.style("font-size","10px")
.append("tspan")
.text('2005 was the only year when')
.append("tspan")
.attr("dy", "1em")
.attr("x", 700)
.text('significantly more movies passed.')
circle = svg.append('circle')
.attr("class", "annotation")
.attr('cx', 731)
.attr('cy', 152)
.attr('r', 10)
.attr('stroke',"black")
.attr('stroke-width',"1")
.attr('fill',"none")
}
// stacked barchart
else{
// create y axis
svg.append("g")
.attr("class", "y axis")
.call(y1Axis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".7em")
.style("text-anchor", "end")
.text("");
// create stacked barchart div
var stacked_barchart = svg.append("g")
.selectAll("g")
// Enter in the stack data = loop key per key = group per group
.data(stackedData)
.enter().append("g")
.attr("fill", function(d) { return color(d.key); })
.selectAll(".stacked_barchart")
// enter a second time = loop subgroup per subgroup to add all rectangles
.data(function(d) { return d})
.enter().append("rect")
// .attr("class", function(d){console.log(d.data.columnDetails.name)}); // can't get hovering to work
// .attr("class", function(d){ return "myRect " + d[1]}) // Add a class to each subgroup: their name
// add transition as well as height and fill
stacked_barchart
.attr("y", 500)
.attr("x", function(d) { return x0(d.data.year); })
.transition()
.delay(function(d,i){return i * 20})
.attr("x", function(d) { return x0(d.data.year); })
.attr("y", function(d) { return y1(d[1]); })
.attr("height", function(d) { return y1(d[0]) - y1(d[1]); })
.attr("width",x1.bandwidth());
// add tooltip
stacked_barchart
.on("mouseover", mouseover)
.on("mousemove", mousemove)
.on("mouseleave", mouseleave)
}
// create legend
var legend = svg.selectAll(".legend")
.data(columnHeaders.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("circle")
.attr("cx", width - 14)
.attr("cy", 9)
.attr("r", 7)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
});
}
</script>