forked from novus/nvd3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nv.d3.js
13048 lines (10152 loc) · 395 KB
/
nv.d3.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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(){
var nv = window.nv || {};
nv.version = '0.0.1a';
nv.dev = true //set false when in production
window.nv = nv;
nv.tooltip = {}; // For the tooltip system
nv.utils = {}; // Utility subsystem
nv.models = {}; //stores all the possible models/components
nv.charts = {}; //stores all the ready to use charts
nv.graphs = []; //stores all the graphs currently on the page
nv.logs = {}; //stores some statistics and potential error messages
nv.dispatch = d3.dispatch('render_start', 'render_end');
// *************************************************************************
// Development render timers - disabled if dev = false
if (nv.dev) {
nv.dispatch.on('render_start', function(e) {
nv.logs.startTime = +new Date();
});
nv.dispatch.on('render_end', function(e) {
nv.logs.endTime = +new Date();
nv.logs.totalTime = nv.logs.endTime - nv.logs.startTime;
nv.log('total', nv.logs.totalTime); // used for development, to keep track of graph generation times
});
}
// ********************************************
// Public Core NV functions
// Logs all arguments, and returns the last so you can test things in place
nv.log = function() {
if (nv.dev && console.log && console.log.apply)
console.log.apply(console, arguments)
else if (nv.dev && console.log && Function.prototype.bind) {
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, arguments);
}
return arguments[arguments.length - 1];
};
nv.render = function render(step) {
step = step || 1; // number of graphs to generate in each timeout loop
nv.render.active = true;
nv.dispatch.render_start();
setTimeout(function() {
var chart, graph;
for (var i = 0; i < step && (graph = nv.render.queue[i]); i++) {
chart = graph.generate();
if (typeof graph.callback == typeof(Function)) graph.callback(chart);
nv.graphs.push(chart);
}
nv.render.queue.splice(0, i);
if (nv.render.queue.length) setTimeout(arguments.callee, 0);
else { nv.render.active = false; nv.dispatch.render_end(); }
}, 0);
};
nv.render.active = false;
nv.render.queue = [];
nv.addGraph = function(obj) {
if (typeof arguments[0] === typeof(Function))
obj = {generate: arguments[0], callback: arguments[1]};
nv.render.queue.push(obj);
if (!nv.render.active) nv.render();
};
nv.identity = function(d) { return d; };
nv.strip = function(s) { return s.replace(/(\s|&)/g,''); };
function daysInMonth(month,year) {
return (new Date(year, month+1, 0)).getDate();
}
function d3_time_range(floor, step, number) {
return function(t0, t1, dt) {
var time = floor(t0), times = [];
if (time < t0) step(time);
if (dt > 1) {
while (time < t1) {
var date = new Date(+time);
if ((number(date) % dt === 0)) times.push(date);
step(time);
}
} else {
while (time < t1) { times.push(new Date(+time)); step(time); }
}
return times;
};
}
d3.time.monthEnd = function(date) {
return new Date(date.getFullYear(), date.getMonth(), 0);
};
d3.time.monthEnds = d3_time_range(d3.time.monthEnd, function(date) {
date.setUTCDate(date.getUTCDate() + 1);
date.setDate(daysInMonth(date.getMonth() + 1, date.getFullYear()));
}, function(date) {
return date.getMonth();
}
);
/*****
* A no-frills tooltip implementation.
*****/
(function() {
var nvtooltip = window.nv.tooltip = {};
nvtooltip.show = function(pos, content, gravity, dist, parentContainer, classes) {
var container = document.createElement('div');
container.className = 'nvtooltip ' + (classes ? classes : 'xy-tooltip');
gravity = gravity || 's';
dist = dist || 20;
var body = parentContainer;
if ( !parentContainer || parentContainer.tagName.match(/g|svg/i)) {
//If the parent element is an SVG element, place tooltip in the <body> element.
body = document.getElementsByTagName('body')[0];
}
container.innerHTML = content;
container.style.left = 0;
container.style.top = 0;
container.style.opacity = 0;
body.appendChild(container);
var height = parseInt(container.offsetHeight),
width = parseInt(container.offsetWidth),
windowWidth = nv.utils.windowSize().width,
windowHeight = nv.utils.windowSize().height,
scrollTop = window.scrollY,
scrollLeft = window.scrollX,
left, top;
windowHeight = window.innerWidth >= document.body.scrollWidth ? windowHeight : windowHeight - 16;
windowWidth = window.innerHeight >= document.body.scrollHeight ? windowWidth : windowWidth - 16;
var tooltipTop = function ( Elem ) {
var offsetTop = top;
do {
if( !isNaN( Elem.offsetTop ) ) {
offsetTop += (Elem.offsetTop);
}
} while( Elem = Elem.offsetParent );
return offsetTop;
}
var tooltipLeft = function ( Elem ) {
var offsetLeft = left;
do {
if( !isNaN( Elem.offsetLeft ) ) {
offsetLeft += (Elem.offsetLeft);
}
} while( Elem = Elem.offsetParent );
return offsetLeft;
}
switch (gravity) {
case 'e':
left = pos[0] - width - dist;
top = pos[1] - (height / 2);
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
if (tLeft < scrollLeft) left = pos[0] + dist > scrollLeft ? pos[0] + dist : scrollLeft - tLeft + left;
if (tTop < scrollTop) top = scrollTop - tTop + top;
if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
break;
case 'w':
left = pos[0] + dist;
top = pos[1] - (height / 2);
if (tLeft + width > windowWidth) left = pos[0] - width - dist;
if (tTop < scrollTop) top = scrollTop + 5;
if (tTop + height > scrollTop + windowHeight) top = scrollTop - height - 5;
break;
case 'n':
left = pos[0] - (width / 2) - 5;
top = pos[1] + dist;
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
if (tLeft < scrollLeft) left = scrollLeft + 5;
if (tLeft + width > windowWidth) left = left - width/2 + 5;
if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
break;
case 's':
left = pos[0] - (width / 2);
top = pos[1] - height - dist;
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
if (tLeft < scrollLeft) left = scrollLeft + 5;
if (tLeft + width > windowWidth) left = left - width/2 + 5;
if (scrollTop > tTop) top = scrollTop;
break;
}
container.style.left = left+'px';
container.style.top = top+'px';
container.style.opacity = 1;
container.style.position = 'absolute'; //fix scroll bar issue
container.style.pointerEvents = 'none'; //fix scroll bar issue
return container;
};
nvtooltip.cleanup = function() {
// Find the tooltips, mark them for removal by this class (so others cleanups won't find it)
var tooltips = document.getElementsByClassName('nvtooltip');
var purging = [];
while(tooltips.length) {
purging.push(tooltips[0]);
tooltips[0].style.transitionDelay = '0 !important';
tooltips[0].style.opacity = 0;
tooltips[0].className = 'nvtooltip-pending-removal';
}
setTimeout(function() {
while (purging.length) {
var removeMe = purging.pop();
removeMe.parentNode.removeChild(removeMe);
}
}, 500);
};
})();
nv.utils.windowSize = function() {
// Sane defaults
var size = {width: 640, height: 480};
// Earlier IE uses Doc.body
if (document.body && document.body.offsetWidth) {
size.width = document.body.offsetWidth;
size.height = document.body.offsetHeight;
}
// IE can use depending on mode it is in
if (document.compatMode=='CSS1Compat' &&
document.documentElement &&
document.documentElement.offsetWidth ) {
size.width = document.documentElement.offsetWidth;
size.height = document.documentElement.offsetHeight;
}
// Most recent browsers use
if (window.innerWidth && window.innerHeight) {
size.width = window.innerWidth;
size.height = window.innerHeight;
}
return (size);
};
// Easy way to bind multiple functions to window.onresize
// TODO: give a way to remove a function after its bound, other than removing all of them
nv.utils.windowResize = function(fun){
var oldresize = window.onresize;
window.onresize = function(e) {
if (typeof oldresize == 'function') oldresize(e);
fun(e);
}
}
// Backwards compatible way to implement more d3-like coloring of graphs.
// If passed an array, wrap it in a function which implements the old default
// behavior
nv.utils.getColor = function(color) {
if (!arguments.length) return nv.utils.defaultColor(); //if you pass in nothing, get default colors back
if( Object.prototype.toString.call( color ) === '[object Array]' )
return function(d, i) { return d.color || color[i % color.length]; };
else
return color;
//can't really help it if someone passes rubbish as color
}
// Default color chooser uses the index of an object as before.
nv.utils.defaultColor = function() {
var colors = d3.scale.category20().range();
return function(d, i) { return d.color || colors[i % colors.length] };
}
// Returns a color function that takes the result of 'getKey' for each series and
// looks for a corresponding color from the dictionary,
nv.utils.customTheme = function(dictionary, getKey, defaultColors) {
getKey = getKey || function(series) { return series.key }; // use default series.key if getKey is undefined
defaultColors = defaultColors || d3.scale.category20().range(); //default color function
var defIndex = defaultColors.length; //current default color (going in reverse)
return function(series, index) {
var key = getKey(series);
if (!defIndex) defIndex = defaultColors.length; //used all the default colors, start over
if (typeof dictionary[key] !== "undefined")
return (typeof dictionary[key] === "function") ? dictionary[key]() : dictionary[key];
else
return defaultColors[--defIndex]; // no match in dictionary, use default color
}
}
// From the PJAX example on d3js.org, while this is not really directly needed
// it's a very cool method for doing pjax, I may expand upon it a little bit,
// open to suggestions on anything that may be useful
nv.utils.pjax = function(links, content) {
d3.selectAll(links).on("click", function() {
history.pushState(this.href, this.textContent, this.href);
load(this.href);
d3.event.preventDefault();
});
function load(href) {
d3.html(href, function(fragment) {
var target = d3.select(content).node();
target.parentNode.replaceChild(d3.select(fragment).select(content).node(), target);
nv.utils.pjax(links, content);
});
}
d3.select(window).on("popstate", function() {
if (d3.event.state) load(d3.event.state);
});
}
/* For situations where we want to approximate the width in pixels for an SVG:text element.
Most common instance is when the element is in a display:none; container.
Forumla is : text.length * font-size * constant_factor
*/
nv.utils.calcApproxTextWidth = function (svgTextElem) {
if (svgTextElem instanceof d3.selection) {
var fontSize = parseInt(svgTextElem.style("font-size").replace("px",""));
var textLength = svgTextElem.text().length;
return textLength * fontSize * 0.5;
}
return 0;
};
nv.models.axis = function() {
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var axis = d3.svg.axis()
;
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 75 //only used for tickLabel currently
, height = 60 //only used for tickLabel currently
, scale = d3.scale.linear()
, axisLabelText = null
, showMaxMin = true //TODO: showMaxMin should be disabled on all ordinal scaled axes
, highlightZero = true
, rotateLabels = 0
, rotateYLabel = true
, staggerLabels = false
, isOrdinal = false
, ticks = null
;
axis
.scale(scale)
.orient('bottom')
.tickFormat(function(d) { return d })
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var scale0;
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this);
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-axis').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-axis');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g')
//------------------------------------------------------------
if (ticks !== null)
axis.ticks(ticks);
else if (axis.orient() == 'top' || axis.orient() == 'bottom')
axis.ticks(Math.abs(scale.range()[1] - scale.range()[0]) / 100);
//TODO: consider calculating width/height based on whether or not label is added, for reference in charts using this component
d3.transition(g)
.call(axis);
scale0 = scale0 || axis.scale();
var fmt = axis.tickFormat();
if (fmt == null) {
fmt = scale0.tickFormat();
}
var axisLabel = g.selectAll('text.nv-axislabel')
.data([axisLabelText || null]);
axisLabel.exit().remove();
switch (axis.orient()) {
case 'top':
axisLabel.enter().append('text').attr('class', 'nv-axislabel');
var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0]));
axisLabel
.attr('text-anchor', 'middle')
.attr('y', 0)
.attr('x', w/2);
if (showMaxMin) {
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text');
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(' + scale(d) + ',0)'
})
.select('text')
.attr('dy', '0em')
.attr('y', -axis.tickPadding())
.attr('text-anchor', 'middle')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
d3.transition(axisMaxMin)
.attr('transform', function(d,i) {
return 'translate(' + scale.range()[i] + ',0)'
});
}
break;
case 'bottom':
var xLabelMargin = 36;
var maxTextWidth = 30;
var xTicks = g.selectAll('g').select("text");
if (rotateLabels%360) {
//Calculate the longest xTick width
xTicks.each(function(d,i){
var width = this.getBBox().width;
if(width > maxTextWidth) maxTextWidth = width;
});
//Convert to radians before calculating sin. Add 30 to margin for healthy padding.
var sin = Math.abs(Math.sin(rotateLabels*Math.PI/180));
var xLabelMargin = (sin ? sin*maxTextWidth : maxTextWidth)+30;
//Rotate all xTicks
xTicks
.attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' })
.attr('text-anchor', rotateLabels%360 > 0 ? 'start' : 'end');
}
axisLabel.enter().append('text').attr('class', 'nv-axislabel');
var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0]));
axisLabel
.attr('text-anchor', 'middle')
.attr('y', xLabelMargin)
.attr('x', w/2);
if (showMaxMin) {
//if (showMaxMin && !isOrdinal) {
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
//.data(scale.domain())
.data([scale.domain()[0], scale.domain()[scale.domain().length - 1]]);
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text');
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(' + (scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0)) + ',0)'
})
.select('text')
.attr('dy', '.71em')
.attr('y', axis.tickPadding())
.attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' })
.attr('text-anchor', rotateLabels ? (rotateLabels%360 > 0 ? 'start' : 'end') : 'middle')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
d3.transition(axisMaxMin)
.attr('transform', function(d,i) {
//return 'translate(' + scale.range()[i] + ',0)'
//return 'translate(' + scale(d) + ',0)'
return 'translate(' + (scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0)) + ',0)'
});
}
if (staggerLabels)
xTicks
.attr('transform', function(d,i) { return 'translate(0,' + (i % 2 == 0 ? '0' : '12') + ')' });
break;
case 'right':
axisLabel.enter().append('text').attr('class', 'nv-axislabel');
axisLabel
.attr('text-anchor', rotateYLabel ? 'middle' : 'begin')
.attr('transform', rotateYLabel ? 'rotate(90)' : '')
.attr('y', rotateYLabel ? (-Math.max(margin.right,width) + 12) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart
.attr('x', rotateYLabel ? (scale.range()[0] / 2) : axis.tickPadding());
if (showMaxMin) {
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text')
.style('opacity', 0);
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(0,' + scale(d) + ')'
})
.select('text')
.attr('dy', '.32em')
.attr('y', 0)
.attr('x', axis.tickPadding())
.attr('text-anchor', 'start')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
d3.transition(axisMaxMin)
.attr('transform', function(d,i) {
return 'translate(0,' + scale.range()[i] + ')'
})
.select('text')
.style('opacity', 1);
}
break;
case 'left':
/*
//For dynamically placing the label. Can be used with dynamically-sized chart axis margins
var yTicks = g.selectAll('g').select("text");
yTicks.each(function(d,i){
var labelPadding = this.getBBox().width + axis.tickPadding() + 16;
if(labelPadding > width) width = labelPadding;
});
*/
axisLabel.enter().append('text').attr('class', 'nv-axislabel');
axisLabel
.attr('text-anchor', rotateYLabel ? 'middle' : 'end')
.attr('transform', rotateYLabel ? 'rotate(-90)' : '')
.attr('y', rotateYLabel ? (-Math.max(margin.left,width) + 12) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart
.attr('x', rotateYLabel ? (-scale.range()[0] / 2) : -axis.tickPadding());
if (showMaxMin) {
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text')
.style('opacity', 0);
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(0,' + scale0(d) + ')'
})
.select('text')
.attr('dy', '.32em')
.attr('y', 0)
.attr('x', -axis.tickPadding())
.attr('text-anchor', 'end')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
d3.transition(axisMaxMin)
.attr('transform', function(d,i) {
return 'translate(0,' + scale.range()[i] + ')'
})
.select('text')
.style('opacity', 1);
}
break;
}
axisLabel
.text(function(d) { return d });
if (showMaxMin && (axis.orient() === 'left' || axis.orient() === 'right')) {
//check if max and min overlap other values, if so, hide the values that overlap
g.selectAll('g') // the g's wrapping each tick
.each(function(d,i) {
d3.select(this).select('text').attr('opacity', 1);
if (scale(d) < scale.range()[1] + 10 || scale(d) > scale.range()[0] - 10) { // 10 is assuming text height is 16... if d is 0, leave it!
if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL
d3.select(this).attr('opacity', 0);
d3.select(this).select('text').attr('opacity', 0); // Don't remove the ZERO line!!
}
});
//if Max and Min = 0 only show min, Issue #281
if (scale.domain()[0] == scale.domain()[1] && scale.domain()[0] == 0)
wrap.selectAll('g.nv-axisMaxMin')
.style('opacity', function(d,i) { return !i ? 1 : 0 });
}
if (showMaxMin && (axis.orient() === 'top' || axis.orient() === 'bottom')) {
var maxMinRange = [];
wrap.selectAll('g.nv-axisMaxMin')
.each(function(d,i) {
try {
if (i) // i== 1, max position
maxMinRange.push(scale(d) - this.getBBox().width - 4) //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case)
else // i==0, min position
maxMinRange.push(scale(d) + this.getBBox().width + 4)
}catch (err) {
if (i) // i== 1, max position
maxMinRange.push(scale(d) - 4) //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case)
else // i==0, min position
maxMinRange.push(scale(d) + 4)
}
});
g.selectAll('g') // the g's wrapping each tick
.each(function(d,i) {
if (scale(d) < maxMinRange[0] || scale(d) > maxMinRange[1]) {
if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL
d3.select(this).remove();
else
d3.select(this).select('text').remove(); // Don't remove the ZERO line!!
}
});
}
//highlight zero line ... Maybe should not be an option and should just be in CSS?
if (highlightZero)
g.selectAll('.tick')
.filter(function(d) { return !parseFloat(Math.round(d.__data__*100000)/1000000) && (d.__data__ !== undefined) }) //this is because sometimes the 0 tick is a very small fraction, TODO: think of cleaner technique
.classed('zero', true);
//store old scales for use in transitions on update
scale0 = scale.copy();
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.axis = axis;
d3.rebind(chart, axis, 'orient', 'tickValues', 'tickSubdivide', 'tickSize', 'tickPadding', 'tickFormat');
d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands'); //these are also accessible by chart.scale(), but added common ones directly for ease of use
chart.margin = function(_) {
if(!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
}
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.ticks = function(_) {
if (!arguments.length) return ticks;
ticks = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.axisLabel = function(_) {
if (!arguments.length) return axisLabelText;
axisLabelText = _;
return chart;
}
chart.showMaxMin = function(_) {
if (!arguments.length) return showMaxMin;
showMaxMin = _;
return chart;
}
chart.highlightZero = function(_) {
if (!arguments.length) return highlightZero;
highlightZero = _;
return chart;
}
chart.scale = function(_) {
if (!arguments.length) return scale;
scale = _;
axis.scale(scale);
isOrdinal = typeof scale.rangeBands === 'function';
d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands');
return chart;
}
chart.rotateYLabel = function(_) {
if(!arguments.length) return rotateYLabel;
rotateYLabel = _;
return chart;
}
chart.rotateLabels = function(_) {
if(!arguments.length) return rotateLabels;
rotateLabels = _;
return chart;
}
chart.staggerLabels = function(_) {
if (!arguments.length) return staggerLabels;
staggerLabels = _;
return chart;
};
//============================================================
return chart;
}
// Chart design based on the recommendations of Stephen Few. Implementation
// based on the work of Clint Ivy, Jamie Love, and Jason Davies.
// http://projects.instantcognition.com/protovis/bulletchart/
nv.models.bullet = function() {
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, orient = 'left' // TODO top & bottom
, reverse = false
, ranges = function(d) { return d.ranges }
, markers = function(d) { return d.markers }
, measures = function(d) { return d.measures }
, forceX = [0] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
, width = 380
, height = 30
, tickFormat = null
, color = nv.utils.getColor(['#1f77b4'])
, dispatch = d3.dispatch('elementMouseover', 'elementMouseout')
;
//============================================================
function chart(selection) {
selection.each(function(d, i) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
var rangez = ranges.call(this, d, i).slice().sort(d3.descending),
markerz = markers.call(this, d, i).slice().sort(d3.descending),
measurez = measures.call(this, d, i).slice().sort(d3.descending);
//------------------------------------------------------------
// Setup Scales
// Compute the new x-scale.
var x1 = d3.scale.linear()
.domain( d3.extent(d3.merge([forceX, rangez])) )
.range(reverse ? [availableWidth, 0] : [0, availableWidth]);
// Retrieve the old x-scale, if this is an update.
var x0 = this.__chart__ || d3.scale.linear()
.domain([0, Infinity])
.range(x1.range());
// Stash the new scale.
this.__chart__ = x1;
var rangeMin = d3.min(rangez), //rangez[2]
rangeMax = d3.max(rangez), //rangez[0]
rangeAvg = rangez[1];
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-bullet').data([d]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bullet');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('rect').attr('class', 'nv-range nv-rangeMax');
gEnter.append('rect').attr('class', 'nv-range nv-rangeAvg');
gEnter.append('rect').attr('class', 'nv-range nv-rangeMin');
gEnter.append('rect').attr('class', 'nv-measure');
gEnter.append('path').attr('class', 'nv-markerTriangle');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0)
w1 = function(d) { return Math.abs(x1(d) - x1(0)) };
var xp0 = function(d) { return d < 0 ? x0(d) : x0(0) },
xp1 = function(d) { return d < 0 ? x1(d) : x1(0) };
g.select('rect.nv-rangeMax')
.attr('height', availableHeight)
.attr('width', w1(rangeMax > 0 ? rangeMax : rangeMin))
.attr('x', xp1(rangeMax > 0 ? rangeMax : rangeMin))
.datum(rangeMax > 0 ? rangeMax : rangeMin)
/*
.attr('x', rangeMin < 0 ?
rangeMax > 0 ?
x1(rangeMin)
: x1(rangeMax)
: x1(0))
*/
g.select('rect.nv-rangeAvg')
.attr('height', availableHeight)
.attr('width', w1(rangeAvg))
.attr('x', xp1(rangeAvg))
.datum(rangeAvg)
/*
.attr('width', rangeMax <= 0 ?
x1(rangeMax) - x1(rangeAvg)
: x1(rangeAvg) - x1(rangeMin))
.attr('x', rangeMax <= 0 ?
x1(rangeAvg)
: x1(rangeMin))
*/
g.select('rect.nv-rangeMin')
.attr('height', availableHeight)
.attr('width', w1(rangeMax))
.attr('x', xp1(rangeMax))
.attr('width', w1(rangeMax > 0 ? rangeMin : rangeMax))
.attr('x', xp1(rangeMax > 0 ? rangeMin : rangeMax))
.datum(rangeMax > 0 ? rangeMin : rangeMax)
/*
.attr('width', rangeMax <= 0 ?
x1(rangeAvg) - x1(rangeMin)
: x1(rangeMax) - x1(rangeAvg))
.attr('x', rangeMax <= 0 ?
x1(rangeMin)
: x1(rangeAvg))
*/
g.select('rect.nv-measure')
.style('fill', color)
.attr('height', availableHeight / 3)
.attr('y', availableHeight / 3)
.attr('width', measurez < 0 ?
x1(0) - x1(measurez[0])
: x1(measurez[0]) - x1(0))
.attr('x', xp1(measurez))
.on('mouseover', function() {
dispatch.elementMouseover({
value: measurez[0],
label: 'Current',
pos: [x1(measurez[0]), availableHeight/2]
})
})
.on('mouseout', function() {
dispatch.elementMouseout({
value: measurez[0],
label: 'Current'
})
})
var h3 = availableHeight / 6;
if (markerz[0]) {
g.selectAll('path.nv-markerTriangle')
.attr('transform', function(d) { return 'translate(' + x1(markerz[0]) + ',' + (availableHeight / 2) + ')' })
.attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z')
.on('mouseover', function() {
dispatch.elementMouseover({
value: markerz[0],
label: 'Previous',
pos: [x1(markerz[0]), availableHeight/2]
})
})
.on('mouseout', function() {
dispatch.elementMouseout({
value: markerz[0],
label: 'Previous'
})
});
} else {
g.selectAll('path.nv-markerTriangle').remove();
}
wrap.selectAll('.nv-range')
.on('mouseover', function(d,i) {
var label = !i ? "Maximum" : i == 1 ? "Mean" : "Minimum";
dispatch.elementMouseover({
value: d,
label: label,
pos: [x1(d), availableHeight/2]
})
})
.on('mouseout', function(d,i) {
var label = !i ? "Maximum" : i == 1 ? "Mean" : "Minimum";
dispatch.elementMouseout({
value: d,
label: label
})
})
/* // THIS IS THE PREVIOUS BULLET IMPLEMENTATION, WILL REMOVE SHORTLY
// Update the range rects.
var range = g.selectAll('rect.nv-range')
.data(rangez);
range.enter().append('rect')
.attr('class', function(d, i) { return 'nv-range nv-s' + i; })
.attr('width', w0)
.attr('height', availableHeight)
.attr('x', reverse ? x0 : 0)
.on('mouseover', function(d,i) {
dispatch.elementMouseover({
value: d,
label: (i <= 0) ? 'Maximum' : (i > 1) ? 'Minimum' : 'Mean', //TODO: make these labels a variable
pos: [x1(d), availableHeight/2]
})
})
.on('mouseout', function(d,i) {
dispatch.elementMouseout({
value: d,
label: (i <= 0) ? 'Minimum' : (i >=1) ? 'Maximum' : 'Mean' //TODO: make these labels a variable
})
})
d3.transition(range)
.attr('x', reverse ? x1 : 0)
.attr('width', w1)
.attr('height', availableHeight);
// Update the measure rects.
var measure = g.selectAll('rect.nv-measure')
.data(measurez);
measure.enter().append('rect')
.attr('class', function(d, i) { return 'nv-measure nv-s' + i; })