-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrushable.html
executable file
·579 lines (462 loc) · 21 KB
/
brushable.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<!-- Google fonts -->
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300,400' rel='stylesheet' type='text/css'>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
body {
font-size: 10px;
font-family: 'Open Sans', sans-serif;
font-weight: 400;
text-align: center;
}
#title {
font-size: 20px;
padding-bottom: 10px;
padding-top: 20px;
font-weight: 300;
}
#explanation {
font-size: 12px;
max-width: 620px;
margin: 0 auto;
padding-top: 10px;
color: #ababab;
font-weight: 300;
}
.axis path,
.axis line {
fill: none;
}
.y.axis path {
display: none;
}
.brush .extent {
fill-opacity: .125;
shape-rendering: crispEdges;
}
.resize {
display: inline !important; /* show when empty */
fill: #7A7A7A;
fill-opacity: 1;
stroke: #7A7A7A;
stroke-width: 2px;
}
.bar {
/*shape-rendering: crispEdges;*/
}
</style>
</head>
<body>
<div id="title">Brushable horizontal bar chart</div>
<div id="chart"></div>
<div id="explanation">You can see more or less of the total bar chart on the left by either dragging the box in the mini chart on the right or by scrolling your mouse. You can also click anywhere in the mini chart to center the box on that region. And you can increase and decrease the size of the box by dragging the top or bottom handle up or down.</div>
<script>
var data = [],
svg,
defs,
gBrush,
brush,
main_xScale,
mini_xScale,
main_yScale,
mini_yScale,
main_yAxis,
mini_width,
brushTotalStart,
brushTotalEnd,
updatedData,
mousewheelTimer,
scrolling = false,
scrollEnd = false;
init();
function init() {
d3.csv('Data/brushable.csv', function ( response ) {
data = response.map(function (item) {
var my_object = {};
my_object.key = item.key;
my_object.country = item.country;
my_object.value = +item.value;
data.push(my_object);
console.log(data)
})});
// Create the random data
// for (var i = 0; i < 5; i++) {
// var my_object = {};
// my_object.key = i;
// my_object.country = makeWord();
// my_object.value = Math.floor(Math.random() * 600);
// data.push(my_object);
// console.log(data)
////
// }//for i
data.sort(function (a, b) {
return b.value - a.value;
});
/////////////////////////////////////////////////////////////
///////////////// Set-up SVG and wrappers ///////////////////
/////////////////////////////////////////////////////////////
//Added only for the mouse wheel
var zoomer = d3.behavior.zoom()
.on("zoom", null);
var main_margin = {top: 10, right: 10, bottom: 10, left: 100},
main_width = 500 - main_margin.left - main_margin.right,
main_height = 400 - main_margin.top - main_margin.bottom;
var mini_margin = {top: 10, right: 10, bottom: 10, left: 10},
mini_height = 400 - mini_margin.top - mini_margin.bottom;
mini_width = 100 - mini_margin.left - mini_margin.right;
svg = d3.select("#chart").append("svg")
.attr("class", "svgWrapper")
.attr("width", main_width + main_margin.left + main_margin.right + mini_width + mini_margin.left + mini_margin.right)
.attr("height", main_height + main_margin.top + main_margin.bottom)
.call(zoomer)
.on("wheel.zoom", scroll)
//.on("mousewheel.zoom", scroll)
//.on("DOMMouseScroll.zoom", scroll)
//.on("MozMousePixelScroll.zoom", scroll)
//Is this needed?
.on("mousedown.zoom", null)
.on("touchstart.zoom", null)
.on("touchmove.zoom", null)
.on("touchend.zoom", null);
var mainGroup = svg.append("g")
.attr("class", "mainGroup")
.attr("transform", "translate(" + main_margin.left + "," + main_margin.top + ")");
var miniGroup = svg.append("g")
.attr("class", "miniGroup")
.attr("transform", "translate(" + (main_margin.left + main_width + main_margin.right + mini_margin.left) + "," + mini_margin.top + ")");
var brushGroup = svg.append("g")
.attr("class", "brushGroup")
.attr("transform", "translate(" + (main_margin.left + main_width + main_margin.right + mini_margin.left) + "," + mini_margin.top + ")");
/////////////////////////////////////////////////////////////
////////////////////// Initiate scales //////////////////////
/////////////////////////////////////////////////////////////
main_xScale = d3.scale.linear().range([0, main_width]);
mini_xScale = d3.scale.linear().range([0, mini_width]);
main_yScale = d3.scale.ordinal().rangeRoundBands([0, main_height], 0.4, 0);
mini_yScale = d3.scale.ordinal().rangeBands([0, mini_height], 0.4, 0);
//Create y axis object
main_yAxis = d3.svg.axis()
.scale(main_yScale)
.orient("left")
.tickSize(0)
.outerTickSize(0);
//Add group for the y axis
mainGroup.append("g")
.attr("class", "y axis")
.attr("transform", "translate(-5,0)");
/////////////////////////////////////////////////////////////
/////////////////////// Update scales ///////////////////////
/////////////////////////////////////////////////////////////
//Update the scales
main_xScale.domain([0, d3.max(data, function (d) {
// console.log(d.value)
return d.value;
})]);
mini_xScale.domain([0, d3.max(data, function (d) {
return d.value;
})]);
main_yScale.domain(data.map(function (d) {
return d.country;
}));
mini_yScale.domain(data.map(function (d) {
return d.country;
}));
//Create the visual part of the y axis
d3.select(".mainGroup").select(".y.axis").call(main_yAxis);
brushTotalStart = mini_yScale.domain()[0];
brushTotalEnd = mini_yScale.domain()[1];
/////////////////////////////////////////////////////////////
///////////////////////// Create brush //////////////////////
/////////////////////////////////////////////////////////////
//What should the first extent of the brush become - a bit arbitrary this
var brushExtent = Math.max(1, Math.min(20, Math.round(data.length * 0.2)));
brush = d3.svg.brush()
.y(mini_yScale)
.extent([mini_yScale(data.country), mini_yScale(data.country)])
.on("brush", brushmove)
.on("brushend", brushend);
//Set up the visual part of the brush
gBrush = d3.select(".brushGroup").append("g")
.attr("class", "brush")
.call(brush);
gBrush.selectAll(".resize")
.append("line")
.attr("x2", mini_width);
gBrush.selectAll(".resize")
.append("path")
.attr("d", d3.svg.symbol().type("triangle-up").size(20))
.attr("transform", function (d, i) {
return i ? "translate(" + (mini_width / 2) + "," + 4 + ") rotate(180)" : "translate(" + (mini_width / 2) + "," + -4 + ") rotate(0)";
});
gBrush.selectAll("rect")
.attr("width", mini_width);
gBrush.select(".background")
.on("mousedown.brush", brushcenter)
.on("touchstart.brush", brushcenter);
///////////////////////////////////////////////////////////////////////////
/////////////////// Create a rainbow gradient - for fun ///////////////////
///////////////////////////////////////////////////////////////////////////
defs = svg.append("defs")
//Create two separate gradients for the main and mini bar - just because it looks fun
createGradient("gradient-rainbow-main", "60%");
createGradient("gradient-rainbow-mini", "13%");
/////////////////////////////////////////////////////////////
//////////////// Set-up the main bar chart //////////////////
/////////////////////////////////////////////////////////////
//DATA JOIN
var bar = d3.select(".mainGroup").selectAll(".bar")
.data(data, function (d) {
return d.key;
});
//UPDATE
bar
.attr("width", function (d) {
return main_xScale(d.value);
})
.attr("y", function (d, i) {
return main_yScale(d.country);
})
.attr("height", main_yScale.rangeBand());
//ENTER
bar.enter().append("rect")
.attr("class", "bar")
.attr("x", 0)
.attr("width", function (d) {
return main_xScale(d.value);
})
.attr("y", function (d, i) {
return main_yScale(d.country);
})
.attr("height", main_yScale.rangeBand())
.style("fill", "url(#gradient-rainbow-main)");
//.style("fill", "#3B8C3D");
//EXIT
bar.exit()
.remove();
/////////////////////////////////////////////////////////////
/////////////// Set-up the mini bar chart ///////////////////
/////////////////////////////////////////////////////////////
//The mini brushable bar
//DATA JOIN
var mini_bar = d3.select(".miniGroup").selectAll(".bar")
.data(data, function (d) {
return d.key;
});
//UDPATE
mini_bar
.attr("width", function(d) { return mini_xScale(d.value); })
.attr("y", function(d,i) { return mini_yScale(d.country); })
.attr("height", mini_yScale.rangeBand());
//ENTER
mini_bar.enter().append("rect")
.attr("class", "bar")
.attr("x", 0)
.attr("width", function(d) { return mini_xScale(d.value); })
.attr("y", function(d,i) { return mini_yScale(d.country); })
.attr("height", mini_yScale.rangeBand())
.style("fill", "url(#gradient-rainbow-mini)");
//.style("fill", "#3B8C3D");
//EXIT
mini_bar.exit()
.remove();
//Start the brush
gBrush.call(brush.event);
}//init
//Function runs on a brush move - to update the big bar chart
function update(data) {
//The transition (& delay) time of the bars and the axis
var transTime = 400;
var delayTime = scrollEnd ? 0 : transTime;
/////////////////////////////////////////////////////////////
///////////////////// Update the axis ///////////////////////
/////////////////////////////////////////////////////////////
//Update the domain of the y scale of the big bar chart
main_yScale.domain(data.map(function(d) { return d.country; }));
//Update the y axis of the big chart
d3.select(".mainGroup")
.select(".y.axis")
.transition()
.duration(transTime).delay(delayTime)
.call(main_yAxis);
/////////////////////////////////////////////////////////////
////////// Update the bars of the main bar chart ////////////
/////////////////////////////////////////////////////////////
//DATA JOIN
var bar = d3.select(".mainGroup").selectAll(".bar")
.data(data, function(d) { return d.key; });
//UPDATE
bar
.transition().duration(transTime).delay(delayTime)
.attr("x", 0)
.attr("width", function(d) { return main_xScale(d.value); })
.attr("y", function(d,i) { return main_yScale(d.country); })
.attr("height", main_yScale.rangeBand());
//ENTER
bar.enter().append("rect")
.attr("class", "bar")
.attr("x", 0)
.attr("width", 0)
.attr("y", function(d,i) { return main_yScale(d.country); })
.attr("height", main_yScale.rangeBand())
.style("fill", "url(#gradient-rainbow-main)")
.transition().duration(transTime).delay(delayTime*2)
.attr("width", function(d) { return main_xScale(d.value); });
//EXIT
bar.exit()
.transition().duration(transTime)
.attr("width", 0)
.remove();
}//update
/////////////////////////////////////////////////////////////
////////////////////// Brush functions //////////////////////
/////////////////////////////////////////////////////////////
//First function that runs on a brush move
function brushmove() {
//What is the extent of the brush
var extent = brush.extent();
//Adjust the extent of the brush so that is snaps to the bars
if (d3.event.mode === "move" || scrollEnd === true) {
//If dragging, preserve the width of the extent
//Does the top edge lie closer to the upper or lower bar
var topExtent = extent[0];
//Using ES5 - http://stackoverflow.com/questions/8584902/get-closest-number-out-of-array
var closestTop = mini_yScale.range().reduce(function (prev, curr) {
return (Math.abs(curr - topExtent) < Math.abs(prev - topExtent) ? curr : prev);
});
//Pixel location of the bottom bar
var maxBar = d3.max(mini_yScale.range());
//Does the top edge lie closer to the upper or lower bar
var bottomExtent = extent[1];
//Using ES5 - http://stackoverflow.com/questions/8584902/get-closest-number-out-of-array
var closestBottom = mini_yScale.range().reduce(function (prev, curr) {
return (Math.abs(curr - bottomExtent) < Math.abs(prev - bottomExtent) ? curr : prev);
});
//Don't let it go over the last bar in the design
if(maxBar === closestBottom) {
//The new extent that snaps to the bars
extent = [closestBottom+mini_yScale.rangeBand()-(extent[1] - extent[0]),closestBottom+mini_yScale.rangeBand()];
} else {
//The new extent that snaps to the bars
extent = [closestTop,closestTop+(extent[1] - extent[0])];
}//else
} else if (!scrolling) {
//If changing size, snap to the nearest rect
//Find the pixel values of the bars that lie within the selected brush
var pixelRanges = mini_yScale.range()
.filter(function(d) { return (d >= extent[0]-mini_yScale.rangeBand()/2) && (d <= extent[1]); });
//The new extent that snaps to the bars within the selection
extent = [d3.min(pixelRanges),d3.max(pixelRanges)+mini_yScale.rangeBand()];
}//else if
//else do nothing - then it comes from the scrolling and the extent has already been determined
//Snap to rect edge - the new extent
d3.select("g.brush")
.call(brush.extent(extent));
//What bars are captured in the brush
//During scrolling take a wider range and don't snap
if( scrolling ) {
var selected = mini_yScale.domain()
.filter(function(d) { return (extent[0]-1e-3-mini_yScale.rangeBand() <= mini_yScale(d)) && (mini_yScale(d) <= extent[1]+1e-3+mini_yScale.rangeBand() ); });
} else {
var selected = mini_yScale.domain()
.filter(function(d) { return (extent[0]-1e-3 <= mini_yScale(d)) && (mini_yScale(d) <= extent[1]+1e-3); });
}
//Take a subset of the selected data from the original dataset
updatedData = data.filter(function(d) { return selected.indexOf(d.country) > -1; });
//Update the colors of the mini chart - Make everything outside the brush grey
d3.select(".miniGroup").selectAll(".bar")
.style("fill", function(d, i) { return selected.indexOf(d.country) > -1 ? "url(#gradient-rainbow-mini)" : "#e0e0e0"; });
////Update the main chart
////If you want to see update during a brush moving uncomment this
////But that doesn't work very well with the transitions of the bars in the update function & scrolling
//update(updatedData);
}//brushmove
//Finally update the data
function brushend() {
if(!scrolling) update(updatedData);
}
//Based on http://bl.ocks.org/mbostock/6498000
//What to do when the user clicks on another location along the brushable bar chart
function brushcenter() {
var target = d3.event.target,
extent = brush.extent(),
size = extent[1] - extent[0],
range = mini_yScale.range(),
y0 = d3.min(range) + size / 2,
y1 = d3.max(range) + mini_yScale.rangeBand() - size / 2,
center = Math.max( y0, Math.min( y1, d3.mouse(target)[1] ) );
d3.event.stopPropagation();
gBrush
.call(brush.extent([center - size / 2, center + size / 2]))
.call(brush.event);
}//brushcenter
/////////////////////////////////////////////////////////////
///////////////////// Scroll functions //////////////////////
/////////////////////////////////////////////////////////////
//Function to calculate what should happen on a mouse scroll
function scroll() {
if (mousewheelTimer) clearTimeout(mousewheelTimer);
var extent = brush.extent(),
size = extent[1] - extent[0],
range = mini_yScale.range(),
y0 = d3.min(range),
y1 = d3.max(range),
dy = d3.event.deltaY,
topSection;
scrolling = true;
if( extent[0] - dy < y0 ) {
topSection = y0;
} else if ( extent[1] - dy > y1 ) {
topSection = y1 - size;
} else {
topSection = extent[0] - dy;
}//else
//Once the person stops scrolling, run the update data function
mousewheelTimer = setTimeout(function() {
mousewheelTimer = null;
scrolling = false;
scrollEnd = true;
//Finally snap the brush and update the data
gBrush
.call(brush.event);
scrollEnd = false;
}, 200);
d3.event.stopPropagation();
d3.event.preventDefault();
//Update the brush position during the scrolling
if(scrolling) {
gBrush
.call(brush.extent([ topSection, topSection + size ]))
.call(brush.event);
}//if
}//scroll
/////////////////////////////////////////////////////////////
///////////////////// Helper functions //////////////////////
/////////////////////////////////////////////////////////////
//Create a gradient
function createGradient(idName, endPerc) {
var coloursRainbow = ["#EFB605", "#E9A501", "#E48405", "#E34914", "#DE0D2B", "#CF003E", "#B90050", "#A30F65", "#8E297E", "#724097", "#4F54A8", "#296DA4", "#0C8B8C", "#0DA471", "#39B15E", "#7EB852"];
defs.append("linearGradient")
.attr("id", idName)
.attr("gradientUnits", "userSpaceOnUse")
.attr("x1", "0%").attr("y1", "0%")
.attr("x2", endPerc).attr("y2", "0%")
.selectAll("stop")
.data(coloursRainbow)
.enter().append("stop")
.attr("offset", function(d,i) { return i/(coloursRainbow.length-1); })
.attr("stop-color", function(d) { return d; });
}//createGradient
//Function to generate random strings of 5 letters - for the demo only
function makeWord() {
var possible_UC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var text = possible_UC.charAt(Math.floor(Math.random() * possible_UC.length));
var possible_LC = "abcdefghijklmnopqrstuvwxyz";
for( var i=0; i < 5; i++ )
text += possible_LC.charAt(Math.floor(Math.random() * possible_LC.length));
return text;
}//makeWord
</script>
</body>
</html>