2 nv.models.cumulativeLineChart = function() {
4 //============================================================
5 // Public Variables with Default Settings
6 //------------------------------------------------------------
8 var lines = nv.models.line()
9 , xAxis = nv.models.axis()
10 , yAxis = nv.models.axis()
11 , legend = nv.models.legend()
12 , controls = nv.models.legend()
13 , interactiveLayer = nv.interactiveGuideline()
16 var margin = {top: 30, right: 30, bottom: 50, left: 60}
17 , color = nv.utils.defaultColor()
23 , rightAlignYAxis = false
26 , useInteractiveGuideline = false
28 , tooltip = function(key, x, y, e, graph) {
29 return '<h3>' + key + '</h3>' +
30 '<p>' + y + ' at ' + x + '</p>'
32 , x //can be accessed via chart.xScale()
33 , y //can be accessed via chart.yScale()
35 , state = { index: 0, rescaleY: rescaleY }
37 , noData = 'No Data Available.'
38 , average = function(d) { return d.average }
39 , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
40 , transitionDuration = 250
48 .orient((rightAlignYAxis) ? 'right' : 'left')
51 //============================================================
52 controls.updateState(false);
54 //============================================================
56 //------------------------------------------------------------
58 var dx = d3.scale.linear()
59 , index = {i: 0, x: 0}
62 var showTooltip = function(e, offsetElement) {
63 var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
64 top = e.pos[1] + ( offsetElement.offsetTop || 0),
65 x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)),
66 y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)),
67 content = tooltip(e.series.key, x, y, e, chart);
69 nv.tooltip.show([left, top], content, null, null, offsetElement);
73 //Moved to see if we can get better behavior to fix issue #315
74 var indexDrag = d3.behavior.drag()
75 .on('dragstart', dragStart)
77 .on('dragend', dragEnd);
79 function dragStart(d,i) {
80 d3.select(chart.container)
81 .style('cursor', 'ew-resize');
84 function dragMove(d,i) {
86 d.i = Math.round(dx.invert(d.x));
88 d3.select(this).attr('transform', 'translate(' + dx(d.i) + ',0)');
92 function dragEnd(d,i) {
93 d3.select(chart.container)
94 .style('cursor', 'auto');
99 //============================================================
102 function chart(selection) {
103 selection.each(function(data) {
104 var container = d3.select(this).classed('nv-chart-' + id, true),
107 var availableWidth = (width || parseInt(container.style('width')) || 960)
108 - margin.left - margin.right,
109 availableHeight = (height || parseInt(container.style('height')) || 400)
110 - margin.top - margin.bottom;
113 chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
114 chart.container = this;
117 state.disabled = data.map(function(d) { return !!d.disabled });
123 if (state[key] instanceof Array)
124 defaultState[key] = state[key].slice(0);
126 defaultState[key] = state[key];
130 var indexDrag = d3.behavior.drag()
131 .on('dragstart', dragStart)
132 .on('drag', dragMove)
133 .on('dragend', dragEnd);
136 function dragStart(d,i) {
137 d3.select(chart.container)
138 .style('cursor', 'ew-resize');
141 function dragMove(d,i) {
142 index.x = d3.event.x;
143 index.i = Math.round(dx.invert(index.x));
147 function dragEnd(d,i) {
148 d3.select(chart.container)
149 .style('cursor', 'auto');
151 // update state and send stateChange with new index
152 state.index = index.i;
153 dispatch.stateChange(state);
156 //------------------------------------------------------------
157 // Display No Data message if there's nothing to show.
159 if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
160 var noDataText = container.selectAll('.nv-noData').data([noData]);
162 noDataText.enter().append('text')
163 .attr('class', 'nvd3 nv-noData')
165 .style('text-anchor', 'middle');
168 .attr('x', margin.left + availableWidth / 2)
169 .attr('y', margin.top + availableHeight / 2)
170 .text(function(d) { return d });
174 container.selectAll('.nv-noData').remove();
177 //------------------------------------------------------------
180 //------------------------------------------------------------
188 var seriesDomains = data
189 .filter(function(series) { return !series.disabled })
190 .map(function(series,i) {
191 var initialDomain = d3.extent(series.values, lines.y());
193 //account for series being disabled when losing 95% or more
194 if (initialDomain[0] < -.95) initialDomain[0] = -.95;
197 (initialDomain[0] - initialDomain[1]) / (1 + initialDomain[1]),
198 (initialDomain[1] - initialDomain[0]) / (1 + initialDomain[0])
202 var completeDomain = [
203 d3.min(seriesDomains, function(d) { return d[0] }),
204 d3.max(seriesDomains, function(d) { return d[1] })
207 lines.yDomain(completeDomain);
213 dx .domain([0, data[0].values.length - 1]) //Assumes all series have same length
214 .range([0, availableWidth])
217 //------------------------------------------------------------
220 var data = indexify(index.i, data);
223 //------------------------------------------------------------
224 // Setup containers and skeleton of chart
225 var interactivePointerEvents = (useInteractiveGuideline) ? "none" : "all";
226 var wrap = container.selectAll('g.nv-wrap.nv-cumulativeLine').data([data]);
227 var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-cumulativeLine').append('g');
228 var g = wrap.select('g');
230 gEnter.append('g').attr('class', 'nv-interactive');
231 gEnter.append('g').attr('class', 'nv-x nv-axis').style("pointer-events","none");
232 gEnter.append('g').attr('class', 'nv-y nv-axis');
233 gEnter.append('g').attr('class', 'nv-background');
234 gEnter.append('g').attr('class', 'nv-linesWrap').style("pointer-events",interactivePointerEvents);
235 gEnter.append('g').attr('class', 'nv-avgLinesWrap').style("pointer-events","none");
236 gEnter.append('g').attr('class', 'nv-legendWrap');
237 gEnter.append('g').attr('class', 'nv-controlsWrap');
240 //------------------------------------------------------------
244 legend.width(availableWidth);
246 g.select('.nv-legendWrap')
250 if ( margin.top != legend.height()) {
251 margin.top = legend.height();
252 availableHeight = (height || parseInt(container.style('height')) || 400)
253 - margin.top - margin.bottom;
256 g.select('.nv-legendWrap')
257 .attr('transform', 'translate(0,' + (-margin.top) +')')
260 //------------------------------------------------------------
263 //------------------------------------------------------------
268 { key: 'Re-scale y-axis', disabled: !rescaleY }
271 controls.width(140).color(['#444', '#444', '#444']);
272 g.select('.nv-controlsWrap')
274 .attr('transform', 'translate(0,' + (-margin.top) +')')
278 //------------------------------------------------------------
281 wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
283 if (rightAlignYAxis) {
284 g.select(".nv-y.nv-axis")
285 .attr("transform", "translate(" + availableWidth + ",0)");
288 // Show error if series goes below 100%
289 var tempDisabled = data.filter(function(d) { return d.tempDisabled });
291 wrap.select('.tempDisabled').remove(); //clean-up and prevent duplicates
292 if (tempDisabled.length) {
293 wrap.append('text').attr('class', 'tempDisabled')
294 .attr('x', availableWidth / 2)
296 .style('text-anchor', 'end')
297 .text(tempDisabled.map(function(d) { return d.key }).join(', ') + ' values cannot be calculated for this time period.');
300 //------------------------------------------------------------
301 // Main Chart Component(s)
303 //------------------------------------------------------------
304 //Set up interactive layer
305 if (useInteractiveGuideline) {
307 .width(availableWidth)
308 .height(availableHeight)
309 .margin({left:margin.left,top:margin.top})
310 .svgContainer(container)
312 wrap.select(".nv-interactive").call(interactiveLayer);
315 gEnter.select('.nv-background')
318 g.select('.nv-background rect')
319 .attr('width', availableWidth)
320 .attr('height', availableHeight);
323 //.x(function(d) { return d.x })
324 .y(function(d) { return d.display.y })
325 .width(availableWidth)
326 .height(availableHeight)
327 .color(data.map(function(d,i) {
328 return d.color || color(d, i);
329 }).filter(function(d,i) { return !data[i].disabled && !data[i].tempDisabled; }));
333 var linesWrap = g.select('.nv-linesWrap')
334 .datum(data.filter(function(d) { return !d.disabled && !d.tempDisabled }));
336 //d3.transition(linesWrap).call(lines);
337 linesWrap.call(lines);
339 /*Handle average lines [AN-612] ----------------------------*/
341 //Store a series index number in the data array.
342 data.forEach(function(d,i) {
346 var avgLineData = data.filter(function(d) {
347 return !d.disabled && !!average(d);
350 var avgLines = g.select(".nv-avgLinesWrap").selectAll("line")
351 .data(avgLineData, function(d) { return d.key; });
353 var getAvgLineY = function(d) {
354 //If average lines go off the svg element, clamp them to the svg bounds.
355 var yVal = y(average(d));
356 if (yVal < 0) return 0;
357 if (yVal > availableHeight) return availableHeight;
363 .style('stroke-width',2)
364 .style('stroke-dasharray','10,10')
365 .style('stroke',function (d,i) {
366 return lines.color()(d,d.seriesIndex);
369 .attr('x2',availableWidth)
370 .attr('y1', getAvgLineY)
371 .attr('y2', getAvgLineY);
374 .style('stroke-opacity',function(d){
375 //If average lines go offscreen, make them transparent
376 var yVal = y(average(d));
377 if (yVal < 0 || yVal > availableHeight) return 0;
381 .attr('x2',availableWidth)
382 .attr('y1', getAvgLineY)
383 .attr('y2', getAvgLineY);
385 avgLines.exit().remove();
387 //Create index line -----------------------------------------
389 var indexLine = linesWrap.selectAll('.nv-indexLine')
391 indexLine.enter().append('rect').attr('class', 'nv-indexLine')
395 .attr('fill-opacity', .5)
396 .style("pointer-events","all")
400 .attr('transform', function(d) { return 'translate(' + dx(d.i) + ',0)' })
401 .attr('height', availableHeight)
403 //------------------------------------------------------------
406 //------------------------------------------------------------
412 //Suggest how many ticks based on the chart width and D3 should listen (70 is the optimal number for MM/DD/YY dates)
413 .ticks( Math.min(data[0].values.length,availableWidth/70) )
414 .tickSize(-availableHeight, 0);
416 g.select('.nv-x.nv-axis')
417 .attr('transform', 'translate(0,' + y.range()[0] + ')');
418 d3.transition(g.select('.nv-x.nv-axis'))
426 .ticks( availableHeight / 36 )
427 .tickSize( -availableWidth, 0);
429 d3.transition(g.select('.nv-y.nv-axis'))
432 //------------------------------------------------------------
435 //============================================================
436 // Event Handling/Dispatching (in chart's scope)
437 //------------------------------------------------------------
440 function updateZero() {
444 //When dragging the index line, turn off line transitions.
445 // Then turn them back on when done dragging.
446 var oldDuration = chart.transitionDuration();
447 chart.transitionDuration(0);
449 chart.transitionDuration(oldDuration);
452 g.select('.nv-background rect')
453 .on('click', function() {
454 index.x = d3.mouse(this)[0];
455 index.i = Math.round(dx.invert(index.x));
457 // update state and send stateChange with new index
458 state.index = index.i;
459 dispatch.stateChange(state);
464 lines.dispatch.on('elementClick', function(e) {
465 index.i = e.pointIndex;
466 index.x = dx(index.i);
468 // update state and send stateChange with new index
469 state.index = index.i;
470 dispatch.stateChange(state);
475 controls.dispatch.on('legendClick', function(d,i) {
476 d.disabled = !d.disabled;
477 rescaleY = !d.disabled;
479 state.rescaleY = rescaleY;
480 dispatch.stateChange(state);
485 legend.dispatch.on('stateChange', function(newState) {
486 state.disabled = newState.disabled;
487 dispatch.stateChange(state);
491 interactiveLayer.dispatch.on('elementMousemove', function(e) {
492 lines.clearHighlights();
493 var singlePoint, pointIndex, pointXLocation, allData = [];
497 .filter(function(series, i) {
498 series.seriesIndex = i;
499 return !series.disabled;
501 .forEach(function(series,i) {
502 pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
503 lines.highlightPoint(i, pointIndex, true);
504 var point = series.values[pointIndex];
505 if (typeof point === 'undefined') return;
506 if (typeof singlePoint === 'undefined') singlePoint = point;
507 if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
510 value: chart.y()(point, pointIndex),
511 color: color(series,series.seriesIndex)
515 //Highlight the tooltip entry based on which point the mouse is closest to.
516 if (allData.length > 2) {
517 var yValue = chart.yScale().invert(e.mouseY);
518 var domainExtent = Math.abs(chart.yScale().domain()[0] - chart.yScale().domain()[1]);
519 var threshold = 0.03 * domainExtent;
520 var indexToHighlight = nv.nearestValueIndex(allData.map(function(d){return d.value}),yValue,threshold);
521 if (indexToHighlight !== null)
522 allData[indexToHighlight].highlight = true;
525 var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex), pointIndex);
526 interactiveLayer.tooltip
527 .position({left: pointXLocation + margin.left, top: e.mouseY + margin.top})
528 .chartContainer(that.parentNode)
530 .valueFormatter(function(d,i) {
531 return yAxis.tickFormat()(d);
540 interactiveLayer.renderGuideLine(pointXLocation);
544 interactiveLayer.dispatch.on("elementMouseout",function(e) {
545 dispatch.tooltipHide();
546 lines.clearHighlights();
549 dispatch.on('tooltipShow', function(e) {
550 if (tooltips) showTooltip(e, that.parentNode);
554 // Update chart from a state object passed to event handler
555 dispatch.on('changeState', function(e) {
557 if (typeof e.disabled !== 'undefined') {
558 data.forEach(function(series,i) {
559 series.disabled = e.disabled[i];
562 state.disabled = e.disabled;
566 if (typeof e.index !== 'undefined') {
568 index.x = dx(index.i);
570 state.index = e.index;
577 if (typeof e.rescaleY !== 'undefined') {
578 rescaleY = e.rescaleY;
584 //============================================================
592 //============================================================
593 // Event Handling/Dispatching (out of chart's scope)
594 //------------------------------------------------------------
596 lines.dispatch.on('elementMouseover.tooltip', function(e) {
597 e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
598 dispatch.tooltipShow(e);
601 lines.dispatch.on('elementMouseout.tooltip', function(e) {
602 dispatch.tooltipHide(e);
605 dispatch.on('tooltipHide', function() {
606 if (tooltips) nv.tooltip.cleanup();
609 //============================================================
612 //============================================================
613 // Expose Public Variables
614 //------------------------------------------------------------
616 // expose chart's sub-components
617 chart.dispatch = dispatch;
619 chart.legend = legend;
622 chart.interactiveLayer = interactiveLayer;
624 d3.rebind(chart, lines, 'defined', 'isArea', 'x', 'y', 'xScale','yScale', 'size', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi','useVoronoi', 'id');
626 chart.options = nv.utils.optionsFunc.bind(chart);
628 chart.margin = function(_) {
629 if (!arguments.length) return margin;
630 margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
631 margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
632 margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
633 margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
637 chart.width = function(_) {
638 if (!arguments.length) return width;
643 chart.height = function(_) {
644 if (!arguments.length) return height;
649 chart.color = function(_) {
650 if (!arguments.length) return color;
651 color = nv.utils.getColor(_);
656 chart.rescaleY = function(_) {
657 if (!arguments.length) return rescaleY;
662 chart.showControls = function(_) {
663 if (!arguments.length) return showControls;
668 chart.useInteractiveGuideline = function(_) {
669 if(!arguments.length) return useInteractiveGuideline;
670 useInteractiveGuideline = _;
672 chart.interactive(false);
673 chart.useVoronoi(false);
678 chart.showLegend = function(_) {
679 if (!arguments.length) return showLegend;
684 chart.showXAxis = function(_) {
685 if (!arguments.length) return showXAxis;
690 chart.showYAxis = function(_) {
691 if (!arguments.length) return showYAxis;
696 chart.rightAlignYAxis = function(_) {
697 if(!arguments.length) return rightAlignYAxis;
699 yAxis.orient( (_) ? 'right' : 'left');
703 chart.tooltips = function(_) {
704 if (!arguments.length) return tooltips;
709 chart.tooltipContent = function(_) {
710 if (!arguments.length) return tooltip;
715 chart.state = function(_) {
716 if (!arguments.length) return state;
721 chart.defaultState = function(_) {
722 if (!arguments.length) return defaultState;
727 chart.noData = function(_) {
728 if (!arguments.length) return noData;
733 chart.average = function(_) {
734 if(!arguments.length) return average;
739 chart.transitionDuration = function(_) {
740 if (!arguments.length) return transitionDuration;
741 transitionDuration = _;
745 //============================================================
748 //============================================================
750 //------------------------------------------------------------
752 /* Normalize the data according to an index point. */
753 function indexify(idx, data) {
754 return data.map(function(line, i) {
758 var v = lines.y()(line.values[idx], idx);
760 //TODO: implement check below, and disable series if series loses 100% or more cause divide by 0 issue
762 //if a series loses more than 100%, calculations fail.. anything close can cause major distortion (but is mathematically correct till it hits 100)
763 line.tempDisabled = true;
767 line.tempDisabled = false;
769 line.values = line.values.map(function(point, pointIndex) {
770 point.display = {'y': (lines.y()(point, pointIndex) - v) / (1 + v) };
778 //============================================================