Merge branch 'i382' of https://github.com/kberg/dygraphs into i382
[dygraphs.git] / dygraph-layout.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
74a5af31
DV
6
7/**
8 * @fileoverview Based on PlotKitLayout, but modified to meet the needs of
9 * dygraphs.
10 */
11
758a629f
DV
12/*jshint globalstrict: true */
13/*global Dygraph:false */
c0f54d4f
DV
14"use strict";
15
74a5af31
DV
16/**
17 * Creates a new DygraphLayout object.
18 *
19 * This class contains all the data to be charted.
20 * It uses data coordinates, but also records the chart range (in data
21 * coordinates) and hence is able to calculate percentage positions ('In this
22 * view, Point A lies 25% down the x-axis.')
23 *
24 * Two things that it does not do are:
25 * 1. Record pixel coordinates for anything.
26 * 2. (oddly) determine anything about the layout of chart elements.
27 *
28 * The naming is a vestige of Dygraph's original PlotKit roots.
29 *
30 * @constructor
31 */
c0f54d4f 32var DygraphLayout = function(dygraph) {
74a5af31 33 this.dygraph_ = dygraph;
758a629f 34 this.datasets = [];
82c6fe4d 35 this.setNames = [];
758a629f 36 this.annotations = [];
74a5af31 37 this.yAxes_ = null;
a12a78ae 38 this.points = null;
74a5af31
DV
39
40 // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
41 // yticks are outputs. Clean this up.
42 this.xTicks_ = null;
43 this.yTicks_ = null;
44};
45
46DygraphLayout.prototype.attr_ = function(name) {
47 return this.dygraph_.attr_(name);
48};
49
50DygraphLayout.prototype.addDataset = function(setname, set_xy) {
82c6fe4d
KW
51 this.datasets.push(set_xy);
52 this.setNames.push(setname);
74a5af31
DV
53};
54
141064ff
DE
55/**
56 * Returns the box which the chart should be drawn in. This is the canvas's
57 * box, less space needed for the axis and chart labels.
58 *
59 * @return {{x: number, y: number, w: number, h: number}}
60 */
70be5ed1 61DygraphLayout.prototype.getPlotArea = function() {
0d216a60 62 return this.area_;
758a629f 63};
70be5ed1 64
ccd9d7c2
PF
65// Compute the box which the chart should be drawn in. This is the canvas's
66// box, less space needed for axis and chart labels.
ec475f44 67// NOTE: This should only be called by Dygraph.predraw_().
0d216a60 68DygraphLayout.prototype.computePlotArea = function() {
ccd9d7c2
PF
69 var area = {
70 // TODO(danvk): per-axis setting.
71 x: 0,
72 y: 0
73 };
f8540c66 74
ccd9d7c2
PF
75 area.w = this.dygraph_.width_ - area.x - this.attr_('rightGap');
76 area.h = this.dygraph_.height_;
6dca682f
DV
77
78 // Let plugins reserve space.
79 var e = {
80 chart_div: this.dygraph_.graphDiv,
81 reserveSpaceLeft: function(px) {
82 var r = {
83 x: area.x,
84 y: area.y,
85 w: px,
86 h: area.h
87 };
88 area.x += px;
89 area.w -= px;
90 return r;
91 },
1c177b6a
DV
92 reserveSpaceRight: function(px) {
93 var r = {
94 x: area.x + area.w - px,
95 y: area.y,
96 w: px,
97 h: area.h
98 };
99 area.w -= px;
100 return r;
101 },
6dca682f
DV
102 reserveSpaceTop: function(px) {
103 var r = {
104 x: area.x,
105 y: area.y,
106 w: area.w,
107 h: px
108 };
109 area.y += px;
110 area.h -= px;
111 return r;
112 },
1c177b6a
DV
113 reserveSpaceBottom: function(px) {
114 var r = {
115 x: area.x,
116 y: area.y + area.h - px,
117 w: area.w,
118 h: px
119 };
120 area.h -= px;
121 return r;
122 },
6dca682f
DV
123 chartRect: function() {
124 return {x:area.x, y:area.y, w:area.w, h:area.h};
125 }
126 };
127 this.dygraph_.cascadeEvents_('layout', e);
128
0d216a60 129 this.area_ = area;
ccd9d7c2
PF
130};
131
74a5af31
DV
132DygraphLayout.prototype.setAnnotations = function(ann) {
133 // The Dygraph object's annotations aren't parsed. We parse them here and
134 // save a copy. If there is no parser, then the user must be using raw format.
135 this.annotations = [];
136 var parse = this.attr_('xValueParser') || function(x) { return x; };
137 for (var i = 0; i < ann.length; i++) {
138 var a = {};
b5481aea 139 if (!ann[i].xval && ann[i].x === undefined) {
74a5af31
DV
140 this.dygraph_.error("Annotations must have an 'x' property");
141 return;
142 }
143 if (ann[i].icon &&
144 !(ann[i].hasOwnProperty('width') &&
145 ann[i].hasOwnProperty('height'))) {
146 this.dygraph_.error("Must set width and height when setting " +
147 "annotation.icon property");
148 return;
149 }
150 Dygraph.update(a, ann[i]);
151 if (!a.xval) a.xval = parse(a.x);
152 this.annotations.push(a);
153 }
154};
155
156DygraphLayout.prototype.setXTicks = function(xTicks) {
157 this.xTicks_ = xTicks;
158};
159
160// TODO(danvk): add this to the Dygraph object's API or move it into Layout.
161DygraphLayout.prototype.setYAxes = function (yAxes) {
162 this.yAxes_ = yAxes;
163};
164
165DygraphLayout.prototype.setDateWindow = function(dateWindow) {
166 this.dateWindow_ = dateWindow;
167};
168
169DygraphLayout.prototype.evaluate = function() {
170 this._evaluateLimits();
171 this._evaluateLineCharts();
172 this._evaluateLineTicks();
173 this._evaluateAnnotations();
174};
175
176DygraphLayout.prototype._evaluateLimits = function() {
fa460473
KW
177 var xlimits = this.dygraph_.xAxisRange();
178 this.minxval = xlimits[0];
179 this.maxxval = xlimits[1];
180 var xrange = xlimits[1] - xlimits[0];
181 this.xscale = (xrange !== 0 ? 1 / xrange : 1.0);
74a5af31
DV
182
183 for (var i = 0; i < this.yAxes_.length; i++) {
184 var axis = this.yAxes_[i];
185 axis.minyval = axis.computedValueRange[0];
186 axis.maxyval = axis.computedValueRange[1];
187 axis.yrange = axis.maxyval - axis.minyval;
758a629f 188 axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);
74a5af31
DV
189
190 if (axis.g.attr_("logscale")) {
191 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
758a629f 192 axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
74a5af31
DV
193 if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
194 axis.g.error('axis ' + i + ' of graph at ' + axis.g +
195 ' can\'t be displayed in log scale for range [' +
196 axis.minyval + ' - ' + axis.maxyval + ']');
197 }
198 }
199 }
200};
201
23db4e07
RK
202DygraphLayout._calcYNormal = function(axis, value, logscale) {
203 if (logscale) {
7f028980
DV
204 return 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale);
205 } else {
206 return 1.0 - ((value - axis.minyval) * axis.yscale);
207 }
208};
209
74a5af31 210DygraphLayout.prototype._evaluateLineCharts = function() {
04c104d7 211 var connectSeparated = this.attr_('connectSeparatedPoints');
a12a78ae
DV
212
213 // series index -> point index in series -> |point| structure
214 this.points = new Array(this.datasets.length);
215
b843b52c
RK
216 // TODO(bhs): these loops are a hot-spot for high-point-count charts. In fact,
217 // on chrome+linux, they are 6 times more expensive than iterating through the
218 // points and drawing the lines. The brunt of the cost comes from allocating
219 // the |point| structures.
d9ab36fa 220 var boundaryIdStart = this.dygraph_.getLeftBoundary_();
a12a78ae 221 for (var setIdx = 0; setIdx < this.datasets.length; setIdx++) {
82c6fe4d
KW
222 var dataset = this.datasets[setIdx];
223 var setName = this.setNames[setIdx];
74a5af31 224 var axis = this.dygraph_.axisPropertiesForSeries(setName);
23db4e07 225 // TODO (konigsberg): use optionsForAxis instead.
8e19509a 226 var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName);
74a5af31 227
a12a78ae
DV
228 // Preallocating the size of points reduces reallocations, and therefore,
229 // calls to collect garbage.
230 var seriesPoints = new Array(dataset.length);
231
74a5af31
DV
232 for (var j = 0; j < dataset.length; j++) {
233 var item = dataset[j];
57915b7a
RK
234 var xValue = DygraphLayout.parseFloat_(item[0]);
235 var yValue = DygraphLayout.parseFloat_(item[1]);
ecf9b464 236
4ab8db0c 237 // Range from 0-1 where 0 represents left and 1 represents right.
7f028980
DV
238 var xNormal = (xValue - this.minxval) * this.xscale;
239 // Range from 0-1 where 0 represents top and 1 represents bottom
23db4e07 240 var yNormal = DygraphLayout._calcYNormal(axis, yValue, logscale);
7f028980 241
a12a78ae
DV
242 // TODO(danvk): drop the point in this case, don't null it.
243 // The nulls create complexity in DygraphCanvasRenderer._drawSeries.
57915b7a 244 if (connectSeparated && item[1] === null) {
b843b52c
RK
245 yValue = null;
246 }
a12a78ae 247 seriesPoints[j] = {
f9414b11
DV
248 x: xNormal,
249 y: yNormal,
250 xval: xValue,
251 yval: yValue,
b616fad1 252 name: setName, // TODO(danvk): is this really necessary?
0c667194 253 idx: j + boundaryIdStart
f9414b11 254 };
74a5af31 255 }
a12a78ae
DV
256
257 this.points[setIdx] = seriesPoints;
74a5af31
DV
258 }
259};
260
57915b7a
RK
261/**
262 * Optimized replacement for parseFloat, which was way too slow when almost
263 * all values were type number, with few edge cases, none of which were strings.
264 */
265DygraphLayout.parseFloat_ = function(val) {
266 // parseFloat(null) is NaN
267 if (val === null) {
268 return NaN;
269 }
270
271 // Assume it's a number or NaN. If it's something else, I'll be shocked.
272 return val;
42a9ebb8 273};
57915b7a 274
74a5af31 275DygraphLayout.prototype._evaluateLineTicks = function() {
758a629f
DV
276 var i, tick, label, pos;
277 this.xticks = [];
278 for (i = 0; i < this.xTicks_.length; i++) {
279 tick = this.xTicks_[i];
280 label = tick.label;
281 pos = this.xscale * (tick.v - this.minxval);
74a5af31
DV
282 if ((pos >= 0.0) && (pos <= 1.0)) {
283 this.xticks.push([pos, label]);
284 }
285 }
286
758a629f
DV
287 this.yticks = [];
288 for (i = 0; i < this.yAxes_.length; i++ ) {
74a5af31
DV
289 var axis = this.yAxes_[i];
290 for (var j = 0; j < axis.ticks.length; j++) {
758a629f
DV
291 tick = axis.ticks[j];
292 label = tick.label;
293 pos = this.dygraph_.toPercentYCoord(tick.v, i);
74a5af31
DV
294 if ((pos >= 0.0) && (pos <= 1.0)) {
295 this.yticks.push([i, pos, label]);
296 }
297 }
298 }
299};
300
301
302/**
303 * Behaves the same way as PlotKit.Layout, but also copies the errors
304 * @private
305 */
306DygraphLayout.prototype.evaluateWithError = function() {
307 this.evaluate();
308 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
309
310 // Copy over the error terms
758a629f 311 var i = 0; // index in this.points
82c6fe4d 312 for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
a12a78ae 313 var points = this.points[setIdx];
74a5af31 314 var j = 0;
82c6fe4d
KW
315 var dataset = this.datasets[setIdx];
316 var setName = this.setNames[setIdx];
7f028980 317 var axis = this.dygraph_.axisPropertiesForSeries(setName);
23db4e07 318 // TODO (konigsberg): use optionsForAxis instead.
8e19509a 319 var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName);
23db4e07 320
758a629f 321 for (j = 0; j < dataset.length; j++, i++) {
74a5af31 322 var item = dataset[j];
57915b7a
RK
323 var xv = DygraphLayout.parseFloat_(item[0]);
324 var yv = DygraphLayout.parseFloat_(item[1]);
74a5af31 325
a12a78ae
DV
326 if (xv == points[j].xval &&
327 yv == points[j].yval) {
57915b7a
RK
328 var errorMinus = DygraphLayout.parseFloat_(item[2]);
329 var errorPlus = DygraphLayout.parseFloat_(item[3]);
7f028980
DV
330
331 var yv_minus = yv - errorMinus;
332 var yv_plus = yv + errorPlus;
23db4e07
RK
333 points[j].y_top = DygraphLayout._calcYNormal(axis, yv_minus, logscale);
334 points[j].y_bottom = DygraphLayout._calcYNormal(axis, yv_plus, logscale);
74a5af31
DV
335 }
336 }
337 }
338};
339
340DygraphLayout.prototype._evaluateAnnotations = function() {
341 // Add the annotations to the point to which they belong.
342 // Make a map from (setName, xval) to annotation for quick lookups.
758a629f 343 var i;
74a5af31 344 var annotations = {};
758a629f 345 for (i = 0; i < this.annotations.length; i++) {
74a5af31
DV
346 var a = this.annotations[i];
347 annotations[a.xval + "," + a.series] = a;
348 }
349
350 this.annotated_points = [];
d570a072
AR
351
352 // Exit the function early if there are no annotations.
353 if (!this.annotations || !this.annotations.length) {
354 return;
355 }
ccd9d7c2 356
d570a072 357 // TODO(antrob): loop through annotations not points.
a12a78ae
DV
358 for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
359 var points = this.points[setIdx];
360 for (i = 0; i < points.length; i++) {
361 var p = points[i];
362 var k = p.xval + "," + p.name;
363 if (k in annotations) {
364 p.annotation = annotations[k];
365 this.annotated_points.push(p);
366 }
74a5af31
DV
367 }
368 }
369};
370
371/**
372 * Convenience function to remove all the data sets from a graph
373 */
374DygraphLayout.prototype.removeAllDatasets = function() {
375 delete this.datasets;
82c6fe4d
KW
376 delete this.setNames;
377 delete this.setPointsLengths;
378 delete this.setPointsOffsets;
758a629f 379 this.datasets = [];
82c6fe4d
KW
380 this.setNames = [];
381 this.setPointsLengths = [];
382 this.setPointsOffsets = [];
74a5af31
DV
383};
384
385/**
386 * Return a copy of the point at the indicated index, with its yval unstacked.
387 * @param int index of point in layout_.points
388 */
a12a78ae
DV
389DygraphLayout.prototype.unstackPointAtIndex = function(setIdx, row) {
390 var point = this.points[setIdx][row];
52ca2280 391 // If the point is missing, no unstacking is necessary
907121a8 392 if (!Dygraph.isValidPoint(point)) {
c6bdcd60
AV
393 return point;
394 }
ccd9d7c2 395
74a5af31 396 // Clone the point since we modify it
ccd9d7c2 397 var unstackedPoint = {};
758a629f
DV
398 for (var pt in point) {
399 unstackedPoint[pt] = point[pt];
74a5af31 400 }
ccd9d7c2 401
74a5af31
DV
402 if (!this.attr_("stackedGraph")) {
403 return unstackedPoint;
404 }
ccd9d7c2
PF
405
406 // The unstacked yval is equal to the current yval minus the yval of the
74a5af31 407 // next point at the same xval.
907121a8
VS
408 // We need to iterate over setIdx just in case some series have invalid values
409 // at current row
410 for(setIdx++; setIdx < this.points.length; setIdx++) {
411 var nextPoint = this.points[setIdx][row];
412 if (nextPoint.xval == point.xval && // should always be true?
413 Dygraph.isValidPoint(nextPoint)) {
414 unstackedPoint.yval -= nextPoint.yval;
415 break; // stop at first valid point
416 }
74a5af31 417 }
ccd9d7c2 418
74a5af31 419 return unstackedPoint;
758a629f 420};