forked from speced/respec
-
Notifications
You must be signed in to change notification settings - Fork 1
/
line.js
715 lines (616 loc) · 28.6 KB
/
line.js
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
charts.line = function(args) {
'use strict';
this.args = args;
this.init = function(args) {
raw_data_transformation(args);
process_line(args);
init(args);
x_axis(args);
y_axis(args);
return this;
};
this.mainPlot = function() {
var svg = mg_get_svg_child_of(args.target);
var g;
var data_median = 0;
var updateTransitionDuration = (args.transition_on_update) ? 1000 : 0;
var mapToY = function(d) {
return d[args.y_accessor];
};
//main area
var area = d3.svg.area()
.x(args.scalefns.xf)
.y0(args.scales.Y.range()[0])
.y1(args.scalefns.yf)
.interpolate(args.interpolate);
//confidence band
var confidence_area;
var existing_band = svg.select('.mg-confidence-band');
if (args.show_confidence_band) {
confidence_area = d3.svg.area()
.x(args.scalefns.xf)
.y0(function(d) {
var l = args.show_confidence_band[0];
return args.scales.Y(d[l]);
})
.y1(function(d) {
var u = args.show_confidence_band[1];
return args.scales.Y(d[u]);
})
.interpolate(args.interpolate);
}
//main line
var line = d3.svg.line()
.x(args.scalefns.xf)
.y(args.scalefns.yf)
.interpolate(args.interpolate);
//for animating line on first load
var flat_line = d3.svg.line()
.x(args.scalefns.xf)
.y(function() { return args.scales.Y(data_median); })
.interpolate(args.interpolate);
//for building the optional legend
var legend = '';
var this_data;
var confidenceBand;
for (var i = args.data.length - 1; i >= 0; i--) {
this_data = args.data[i];
//override increment if we have a custom increment series
var line_id = i + 1;
if (args.custom_line_color_map.length > 0) {
line_id = args.custom_line_color_map[i];
}
args.data[i].line_id = line_id;
//add confidence band
if (args.show_confidence_band) {
if (!existing_band.empty()) {
confidenceBand = existing_band
.transition()
.duration(function() {
return (args.transition_on_update) ? 1000 : 0;
});
} else {
confidenceBand = svg.append('path')
.attr('class', 'mg-confidence-band');
}
confidenceBand
.attr('d', confidence_area(args.data[i]))
.attr('clip-path', 'url(#mg-plot-window-'+ mg_strip_punctuation(args.target)+')');
}
//add the area
//var $area = $(args.target).find('svg path.mg-area' + (line_id) + '-color');
var areas = svg.selectAll('.mg-area' + (line_id) + '-color');
var displayArea = args.area && !args.use_data_y_min && !args.y_axis_negative && args.data.length <= 1;
if (displayArea) {
//if area already exists, transition it
if (!areas.empty()) {
//$(svg.node()).find('.mg-y-axis').after($area.detach());
svg.select('.mg-y-axis').node().parentNode.appendChild(areas.node());
areas
.transition()
.duration(updateTransitionDuration)
.attr('d', area(args.data[i]))
.attr('clip-path', 'url(#mg-plot-window'+ mg_strip_punctuation(args.target)+')');
} else { //otherwise, add the area
svg.append('path')
.attr('class', 'mg-main-area ' + 'mg-area' + (line_id) + '-color')
.attr('d', area(args.data[i]))
.attr('clip-path', 'url(#mg-plot-window-' + mg_strip_punctuation(args.target) + ')');
}
} else if (!areas.empty()) {
areas.remove();
}
//add the line, if it already exists, transition the fine gentleman
var existing_line = svg.select('path.mg-main-line.mg-line' + (line_id) + '-color');
if (!existing_line.empty()) {
//$(svg.node()).find('.mg-y-axis').after($(existing_line.node()).detach());
svg.select('.mg-y-axis').node().parentNode.appendChild(existing_line.node());
var lineTransition = existing_line
.transition()
.duration(updateTransitionDuration);
if (!displayArea) {
lineTransition.attrTween('d', pathTween(line(args.data[i]), 4));
} else {
lineTransition.attr('d', line(args.data[i]));
}
}
else { //otherwise...
//if we're animating on load, animate the line from its median value
if (args.animate_on_load) {
data_median = d3.median(args.data[i], mapToY);
svg.append('path')
.attr('class', 'mg-main-line ' + 'mg-line' + (line_id) + '-color')
.attr('d', flat_line(args.data[i]))
.transition()
.duration(1000)
.attr('d', line(args.data[i]))
.attr('clip-path', 'url(#mg-plot-window-' + mg_strip_punctuation(args.target) + ')');
} else { //or just add the line
svg.append('path')
.attr('class', 'mg-main-line ' + 'mg-line' + (line_id) + '-color')
.attr('d', line(args.data[i]))
.attr('clip-path', 'url(#mg-plot-window-' + mg_strip_punctuation(args.target) + ')');
}
}
if (args.missing_is_hidden) {
var the_line = svg.select('.mg-line' + (line_id) + '-color');
var bits = the_line.attr('d').split('L');
var zero = args.scales.Y(0);
var dasharray = [];
var singleton_point_length = 2;
var x_y,
x_y_plus_1,
x,
y,
x_plus_1,
y_plus_1,
segment_length,
cumulative_segment_length = 0;
bits[0] = bits[0].replace('M', '');
bits[bits.length - 1] = bits[bits.length - 1].replace('Z', '');
//if we have a min_x, turn the line off first
if (args.min_x) {
dasharray.push(0);
}
//build the stroke-dasharray pattern
for (var j = 0; j < bits.length - 1; j++) {
x_y = bits[j].split(',');
x_y_plus_1 = bits[j + 1].split(',');
x = Number(x_y[0]);
y = Number(x_y[1]);
x_plus_1 = Number(x_y_plus_1[0]);
y_plus_1 = Number(x_y_plus_1[1]);
segment_length = Math.sqrt(Math.pow(x - x_plus_1, 2) + Math.pow(y - y_plus_1, 2));
//do we need to either cover or clear the current stroke
if (y_plus_1 == zero && y != zero) {
dasharray.push(cumulative_segment_length || singleton_point_length);
cumulative_segment_length = (cumulative_segment_length)
? segment_length
: segment_length - singleton_point_length;
} else if (y_plus_1 != zero && y == zero) { //switching on line
dasharray.push(cumulative_segment_length += segment_length);
cumulative_segment_length = 0;
} else {
cumulative_segment_length += segment_length;
}
}
//fear not, end bit of line, ye too shall be covered
if (dasharray.length > 0) {
dasharray.push(the_line.node().getTotalLength() - dasharray[dasharray.length - 1]);
svg.select('.mg-line' + (line_id) + '-color')
.attr('stroke-dasharray', dasharray.join());
}
}
//build legend
if (args.legend) {
legend = "<span class='mg-line" + line_id + "-legend-color'>— "
+ args.legend[i] + " </span>" + legend;
}
}
if (args.legend) {
d3.select(args.legend_target).html(legend);
}
return this;
};
this.markers = function() {
markers(args);
return this;
};
this.rollover = function() {
var svg = mg_get_svg_child_of(args.target);
var g;
//remove the old rollovers if they already exist
svg.selectAll('.mg-rollover-rect').remove();
svg.selectAll('.mg-voronoi').remove();
//remove the old rollover text and circle if they already exist
svg.selectAll('.mg-active-datapoint').remove();
svg.selectAll('.mg-line-rollover-circle').remove();
svg.selectAll('.mg-active-datapoint-container').remove();
//rollover text
svg.append('g')
.attr('class', 'mg-active-datapoint-container')
.attr('transform', 'translate(' + (args.width - args.right) + ',' + (args.top / 2) + ')')
.append('text')
.attr('class', 'mg-active-datapoint')
.classed('mg-active-datapoint-small', args.use_small_class)
.attr('xml:space', 'preserve')
.attr('text-anchor', 'end');
//append circle
svg.selectAll('.mg-line-rollover-circle')
.data(args.data).enter()
.append('circle')
.attr({
'class': function(d, i) {
return [
'mg-line-rollover-circle',
'mg-line' + d.line_id + '-color',
'mg-area' + d.line_id + '-color'
].join(' ');
},
'cx': 0,
'cy': 0,
'r': 0
});
//update our data by setting a unique line id for each series
//increment from 1... unless we have a custom increment series
var line_id = 1;
for (var i = 0; i < args.data.length; i++) {
for (var j = 0; j < args.data[i].length; j++) {
//if custom line-color map is set, use that instead of line_id
if (args.custom_line_color_map.length > 0) {
args.data[i][j].line_id = args.custom_line_color_map[i];
} else {
args.data[i][j].line_id = line_id;
}
}
line_id++;
}
var data_nested;
var xf;
//for multi-line, use voronoi
if (args.data.length > 1 && !args.aggregate_rollover) {
//main rollover
var voronoi = d3.geom.voronoi()
.x(function(d) { return args.scales.X(d[args.x_accessor]).toFixed(2); })
.y(function(d) { return args.scales.Y(d[args.y_accessor]).toFixed(2); })
.clipExtent([[args.buffer, args.buffer], [args.width - args.buffer, args.height - args.buffer]]);
g = svg.append('g')
.attr('class', 'mg-voronoi');
//we'll be using these when constructing the voronoi rollovers
data_nested = d3.nest()
.key(function(d) {
return args.scales.X(d[args.x_accessor]) + ","
+ args.scales.Y(d[args.y_accessor]);
})
.rollup(function(v) { return v[0]; })
.entries(d3.merge(args.data.map(function(d) { return d; })))
.map(function(d) { return d.values; });
//add the voronoi rollovers
g.selectAll('path')
.data(voronoi(data_nested))
.enter()
.append('path')
.filter(function(d) { return d !== undefined; })
.attr("d", function(d) { return "M" + d.join("L") + "Z"; })
.datum(function(d) { return d.point; }) //because of d3.nest, reassign d
.attr('class', function(d) {
if (args.linked) {
var v = d[args.x_accessor];
var formatter = d3.time.format(args.linked_format);
//only format when x-axis is date
var id = (typeof v === 'number')
? i
: formatter(v);
return 'mg-line' + d.line_id + '-color ' + 'roll_' + id;
} else {
return 'mg-line' + d.line_id + '-color';
}
})
.on('mouseover', this.rolloverOn(args))
.on('mouseout', this.rolloverOff(args))
.on('mousemove', this.rolloverMove(args));
}
// for multi-lines and aggregated rollovers, use rects
else if (args.data.length > 1 && args.aggregate_rollover) {
data_nested = d3.nest()
.key(function(d) { return d[args.x_accessor]; })
.entries(d3.merge(args.data));
xf = data_nested.map(function(di) {
return args.scales.X(new Date(di.key));
});
g = svg.append('g')
.attr('class', 'mg-rollover-rect');
g.selectAll('.mg-rollover-rects')
.data(data_nested).enter()
.append('rect')
.attr('x', function(d, i) {
//if data set is of length 1
if(xf.length === 1) {
return args.left + args.buffer;
} else if (i === 0) {
return xf[i].toFixed(2);
} else {
return ((xf[i-1] + xf[i])/2).toFixed(2);
}
})
.attr('y', args.top)
.attr('width', function(d, i) {
//if data set is of length 1
if(xf.length === 1) {
return args.width - args.right - args.buffer;
} else if (i === 0) {
return ((xf[i+1] - xf[i]) / 2).toFixed(2);
} else if (i == xf.length - 1) {
return ((xf[i] - xf[i-1]) / 2).toFixed(2);
} else {
return ((xf[i+1] - xf[i-1]) / 2).toFixed(2);
}
})
.attr('height', args.height - args.bottom - args.top - args.buffer)
.attr('opacity', 0)
.on('mouseover', this.rolloverOn(args))
.on('mouseout', this.rolloverOff(args))
.on('mousemove', this.rolloverMove(args));
}
//for single line, use rects
else {
//set to 1 unless we have a custom increment series
line_id = 1;
if (args.custom_line_color_map.length > 0) {
line_id = args.custom_line_color_map[0];
}
g = svg.append('g')
.attr('class', 'mg-rollover-rect');
xf = args.data[0].map(args.scalefns.xf);
g.selectAll('.mg-rollover-rects')
.data(args.data[0]).enter()
.append('rect')
.attr('class', function(d, i) {
if (args.linked) {
var v = d[args.x_accessor];
var formatter = d3.time.format(args.linked_format);
//only format when x-axis is date
var id = (typeof v === 'number')
? i
: formatter(v);
return 'mg-line' + line_id + '-color ' + 'roll_' + id;
} else {
return 'mg-line' + line_id + '-color';
}
})
.attr('x', function(d, i) {
//if data set is of length 1
if (xf.length === 1) {
return args.left + args.buffer;
} else if (i === 0) {
return xf[i].toFixed(2);
} else {
return ((xf[i-1] + xf[i])/2).toFixed(2);
}
})
.attr('y', function(d, i) {
return (args.data.length > 1)
? args.scalefns.yf(d) - 6 //multi-line chart sensitivity
: args.top;
})
.attr('width', function(d, i) {
//if data set is of length 1
if (xf.length === 1) {
return args.width - args.right - args.buffer;
} else if (i === 0) {
return ((xf[i+1] - xf[i]) / 2).toFixed(2);
} else if (i === xf.length - 1) {
return ((xf[i] - xf[i-1]) / 2).toFixed(2);
} else {
return ((xf[i+1] - xf[i-1]) / 2).toFixed(2);
}
})
.attr('height', function(d, i) {
return (args.data.length > 1)
? 12 //multi-line chart sensitivity
: args.height - args.bottom - args.top - args.buffer;
})
.attr('opacity', 0)
.on('mouseover', this.rolloverOn(args))
.on('mouseout', this.rolloverOff(args))
.on('mousemove', this.rolloverMove(args));
}
//if the dataset is of length 1, trigger the rollover for our solitary rollover rect
if (args.data.length == 1 && args.data[0].length == 1) {
d3.select('.mg-rollover-rect .mg-line1-color')
.on('mouseover')(args.data[0][0], 0);
}
return this;
};
this.rolloverOn = function(args) {
var svg = mg_get_svg_child_of(args.target);
var fmt;
switch(args.processed.x_time_frame) {
case 'seconds':
fmt = d3.time.format('%b %e, %Y %H:%M:%S');
break;
case 'less-than-a-day':
fmt = d3.time.format('%b %e, %Y %I:%M%p');
break;
case 'four-days':
fmt = d3.time.format('%b %e, %Y %I:%M%p');
break;
default:
fmt = d3.time.format('%b %e, %Y');
}
return function(d, i) {
if (args.aggregate_rollover && args.data.length > 1) {
// hide the circles in case a non-contiguous series is present
svg.selectAll('circle.mg-line-rollover-circle')
.style('opacity', 0);
d.values.forEach(function(datum) {
if (datum[args.x_accessor] >= args.processed.min_x &&
datum[args.x_accessor] <= args.processed.max_x &&
datum[args.y_accessor] >= args.processed.min_y &&
datum[args.y_accessor] <= args.processed.max_y
){
var circle = svg.select('circle.mg-line' + datum.line_id + '-color')
.attr({
'cx': function() {
return args.scales.X(datum[args.x_accessor]).toFixed(2);
},
'cy': function() {
return args.scales.Y(datum[args.y_accessor]).toFixed(2);
},
'r': args.point_size
})
.style('opacity', 1);
}
});
} else if (args.missing_is_hidden && d[args.y_accessor] == 0) {
//disable rollovers for hidden parts of the line
return;
} else {
//show circle on mouse-overed rect
if (d[args.x_accessor] >= args.processed.min_x &&
d[args.x_accessor] <= args.processed.max_x &&
d[args.y_accessor] >= args.processed.min_y &&
d[args.y_accessor] <= args.processed.max_y
){
svg.selectAll('circle.mg-line-rollover-circle')
.attr('class', "")
.attr('class', 'mg-area' + d.line_id + '-color')
.classed('mg-line-rollover-circle', true)
.attr('cx', function() {
return args.scales.X(d[args.x_accessor]).toFixed(2);
})
.attr('cy', function() {
return args.scales.Y(d[args.y_accessor]).toFixed(2);
})
.attr('r', args.point_size)
.style('opacity', 1);
}
//trigger mouseover on all rects for this date in .linked charts
if (args.linked && !MG.globals.link) {
MG.globals.link = true;
var v = d[args.x_accessor];
var formatter = d3.time.format(args.linked_format);
//only format when y-axis is date
var id = (typeof v === 'number')
? i
: formatter(v);
//trigger mouseover on matching line in .linked charts
d3.selectAll('.mg-line' + d.line_id + '-color.roll_' + id)
.each(function(d, i) {
d3.select(this).on('mouseover')(d,i);
});
}
}
svg.selectAll('text')
.filter(function(g, j) {
return d === g;
})
.attr('opacity', 0.3);
var num = rolloverNumberFormatter(args);
//update rollover text
if (args.show_rollover_text) {
var textContainer = svg.select('.mg-active-datapoint'),
lineCount = 0,
lineHeight = 1.1;
textContainer.select('*').remove();
if (args.aggregate_rollover && args.data.length > 1) {
if (args.time_series) {
var date = new Date(d.key);
textContainer.append('tspan')
.text((fmt(date) + ' ' + args.yax_units).trim());
lineCount = 1;
d.values.forEach(function(datum) {
var label = textContainer.append('tspan')
.attr({
x: 0,
y: (lineCount * lineHeight) + 'em'
})
.text(num(datum[args.y_accessor]));
textContainer.append('tspan')
.attr({
x: -label.node().getComputedTextLength(),
y: (lineCount * lineHeight) + 'em'
})
.text('\u2014 ') // mdash
.classed('mg-hover-line' + datum.line_id + '-color', true)
.style('font-weight', 'bold');
lineCount++;
});
textContainer.append('tspan')
.attr('x', 0)
.attr('y', (lineCount * lineHeight) + 'em')
.text('\u00A0');
} else {
d.values.forEach(function(datum) {
var label = textContainer.append('tspan')
.attr({
x: 0,
y: (lineCount * lineHeight) + 'em'
})
.text(args.x_accessor + ': ' + datum[args.x_accessor]
+ ', ' + args.y_accessor + ': ' + args.yax_units
+ num(datum[args.y_accessor]));
textContainer.append('tspan')
.attr({
x: -label.node().getComputedTextLength(),
y: (lineCount * lineHeight) + 'em'
})
.text('\u2014 ') // mdash
.classed('mg-hover-line' + datum.line_id + '-color', true)
.style('font-weight', 'bold');
lineCount++;
});
}
// append an blank ( ) line to mdash positioning
textContainer.append('tspan')
.attr('x', 0)
.attr('y', (lineCount * lineHeight) + 'em')
.text('\u00A0');
} else {
if (args.time_series) {
var dd = new Date(+d[args.x_accessor]);
dd.setDate(dd.getDate());
textContainer.append('tspan')
.text(fmt(dd) + ' ' + args.yax_units
+ num(d[args.y_accessor]));
}
else {
textContainer.append('tspan')
.text(args.x_accessor + ': ' + d[args.x_accessor]
+ ', ' + args.y_accessor + ': ' + args.yax_units
+ num(d[args.y_accessor]));
}
}
}
if (args.mouseover) {
args.mouseover(d, i);
}
};
};
this.rolloverOff = function(args) {
var svg = mg_get_svg_child_of(args.target);
return function(d, i) {
if (args.linked && MG.globals.link) {
MG.globals.link = false;
var v = d[args.x_accessor];
var formatter = d3.time.format(args.linked_format);
//only format when y-axis is date
var id = (typeof v === 'number')
? i
: formatter(v);
d3.selectAll('.roll_' + id)
.each(function(d, i) {
d3.select(this).on('mouseout')(d);
});
}
//remove active datapoint text on mouse out, except if we have a single
svg.selectAll('circle.mg-line-rollover-circle')
.style('opacity', function() {
if (args.data.length == 1 && args.data[0].length == 1) {
return 1;
}
else {
return 0;
}
});
svg.select('.mg-active-datapoint')
.text('');
if (args.mouseout) {
args.mouseout(d, i);
}
};
};
this.rolloverMove = function(args) {
return function(d, i) {
if (args.mousemove) {
args.mousemove(d, i);
}
};
};
this.windowListeners = function() {
mg_window_listeners(this.args);
return this;
};
this.init(args);
return this;
};