Merge branch 'master' into pluggable-renderer
[dygraphs.git] / dygraph-layout.js
1 /**
2 * @license
3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
8 * @fileoverview Based on PlotKitLayout, but modified to meet the needs of
9 * dygraphs.
10 */
11
12 /*jshint globalstrict: true */
13 /*global Dygraph:false */
14 "use strict";
15
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 */
32 var DygraphLayout = function(dygraph) {
33 this.dygraph_ = dygraph;
34 this.datasets = [];
35 this.setNames = [];
36 this.annotations = [];
37 this.yAxes_ = null;
38
39 // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
40 // yticks are outputs. Clean this up.
41 this.xTicks_ = null;
42 this.yTicks_ = null;
43 };
44
45 DygraphLayout.prototype.attr_ = function(name) {
46 return this.dygraph_.attr_(name);
47 };
48
49 DygraphLayout.prototype.addDataset = function(setname, set_xy) {
50 this.datasets.push(set_xy);
51 this.setNames.push(setname);
52 };
53
54 DygraphLayout.prototype.getPlotArea = function() {
55 return this.computePlotArea_();
56 };
57
58 // Compute the box which the chart should be drawn in. This is the canvas's
59 // box, less space needed for axis and chart labels.
60 DygraphLayout.prototype.computePlotArea_ = function() {
61 var area = {
62 // TODO(danvk): per-axis setting.
63 x: 0,
64 y: 0
65 };
66 if (this.attr_('drawYAxis')) {
67 area.x = this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize');
68 }
69
70 area.w = this.dygraph_.width_ - area.x - this.attr_('rightGap');
71 area.h = this.dygraph_.height_;
72
73 // Let plugins reserve space.
74 var e = {
75 chart_div: this.dygraph_.graphDiv,
76 reserveSpaceLeft: function(px) {
77 var r = {
78 x: area.x,
79 y: area.y,
80 w: px,
81 h: area.h
82 };
83 area.x += px;
84 area.w -= px;
85 return r;
86 },
87 reserveSpaceRight: function(px) {
88 var r = {
89 x: area.x + area.w - px,
90 y: area.y,
91 w: px,
92 h: area.h
93 };
94 area.w -= px;
95 return r;
96 },
97 reserveSpaceTop: function(px) {
98 var r = {
99 x: area.x,
100 y: area.y,
101 w: area.w,
102 h: px
103 };
104 area.y += px;
105 area.h -= px;
106 return r;
107 },
108 reserveSpaceBottom: function(px) {
109 var r = {
110 x: area.x,
111 y: area.y + area.h - px,
112 w: area.w,
113 h: px
114 };
115 area.h -= px;
116 return r;
117 },
118 chartRect: function() {
119 return {x:area.x, y:area.y, w:area.w, h:area.h};
120 }
121 };
122 this.dygraph_.cascadeEvents_('layout', e);
123
124 if (this.attr_('drawXAxis')) {
125 if (this.attr_('xAxisHeight')) {
126 area.h -= this.attr_('xAxisHeight');
127 } else {
128 area.h -= this.attr_('axisLabelFontSize') + 2 * this.attr_('axisTickSize');
129 }
130 }
131
132 // Shrink the drawing area to accomodate additional y-axes.
133 if (this.dygraph_.numAxes() == 2) {
134 // TODO(danvk): per-axis setting.
135 area.w -= (this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize'));
136 } else if (this.dygraph_.numAxes() > 2) {
137 this.dygraph_.error("Only two y-axes are supported at this time. (Trying " +
138 "to use " + this.dygraph_.numAxes() + ")");
139 }
140
141 // Add space for range selector, if needed.
142 if (this.attr_('showRangeSelector')) {
143 area.h -= this.attr_('rangeSelectorHeight') + 4;
144 }
145
146 return area;
147 };
148
149 DygraphLayout.prototype.setAnnotations = function(ann) {
150 // The Dygraph object's annotations aren't parsed. We parse them here and
151 // save a copy. If there is no parser, then the user must be using raw format.
152 this.annotations = [];
153 var parse = this.attr_('xValueParser') || function(x) { return x; };
154 for (var i = 0; i < ann.length; i++) {
155 var a = {};
156 if (!ann[i].xval && !ann[i].x) {
157 this.dygraph_.error("Annotations must have an 'x' property");
158 return;
159 }
160 if (ann[i].icon &&
161 !(ann[i].hasOwnProperty('width') &&
162 ann[i].hasOwnProperty('height'))) {
163 this.dygraph_.error("Must set width and height when setting " +
164 "annotation.icon property");
165 return;
166 }
167 Dygraph.update(a, ann[i]);
168 if (!a.xval) a.xval = parse(a.x);
169 this.annotations.push(a);
170 }
171 };
172
173 DygraphLayout.prototype.setXTicks = function(xTicks) {
174 this.xTicks_ = xTicks;
175 };
176
177 // TODO(danvk): add this to the Dygraph object's API or move it into Layout.
178 DygraphLayout.prototype.setYAxes = function (yAxes) {
179 this.yAxes_ = yAxes;
180 };
181
182 DygraphLayout.prototype.setDateWindow = function(dateWindow) {
183 this.dateWindow_ = dateWindow;
184 };
185
186 DygraphLayout.prototype.evaluate = function() {
187 this._evaluateLimits();
188 this._evaluateLineCharts();
189 this._evaluateLineTicks();
190 this._evaluateAnnotations();
191 };
192
193 DygraphLayout.prototype._evaluateLimits = function() {
194 this.minxval = this.maxxval = null;
195 if (this.dateWindow_) {
196 this.minxval = this.dateWindow_[0];
197 this.maxxval = this.dateWindow_[1];
198 } else {
199 for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
200 var series = this.datasets[setIdx];
201 if (series.length > 1) {
202 var x1 = series[0][0];
203 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
204
205 var x2 = series[series.length - 1][0];
206 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
207 }
208 }
209 }
210 this.xrange = this.maxxval - this.minxval;
211 this.xscale = (this.xrange !== 0 ? 1/this.xrange : 1.0);
212
213 for (var i = 0; i < this.yAxes_.length; i++) {
214 var axis = this.yAxes_[i];
215 axis.minyval = axis.computedValueRange[0];
216 axis.maxyval = axis.computedValueRange[1];
217 axis.yrange = axis.maxyval - axis.minyval;
218 axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);
219
220 if (axis.g.attr_("logscale")) {
221 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
222 axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
223 if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
224 axis.g.error('axis ' + i + ' of graph at ' + axis.g +
225 ' can\'t be displayed in log scale for range [' +
226 axis.minyval + ' - ' + axis.maxyval + ']');
227 }
228 }
229 }
230 };
231
232 DygraphLayout._calcYNormal = function(axis, value) {
233 if (axis.logscale) {
234 return 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale);
235 } else {
236 return 1.0 - ((value - axis.minyval) * axis.yscale);
237 }
238 };
239
240 DygraphLayout.prototype._evaluateLineCharts = function() {
241 // An array to keep track of how many points will be drawn for each set.
242 // This will allow for the canvas renderer to not have to check every point
243 // for every data set since the points are added in order of the sets in
244 // datasets.
245 this.setPointsLengths = [];
246 this.setPointsOffsets = [];
247
248 var connectSeparated = this.attr_('connectSeparatedPoints');
249 // TODO(bhs): these loops are a hot-spot for high-point-count charts. In fact,
250 // on chrome+linux, they are 6 times more expensive than iterating through the
251 // points and drawing the lines. The brunt of the cost comes from allocating
252 // the |point| structures.
253 var i = 0;
254 var setIdx;
255
256 // Preallocating the size of points reduces reallocations, and therefore,
257 // calls to collect garbage.
258 var totalPoints = 0;
259 for (setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
260 totalPoints += this.datasets[setIdx].length;
261 }
262 this.points = new Array(totalPoints);
263
264 for (setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
265 this.setPointsOffsets.push(i);
266 var dataset = this.datasets[setIdx];
267 var setName = this.setNames[setIdx];
268 var axis = this.dygraph_.axisPropertiesForSeries(setName);
269
270 for (var j = 0; j < dataset.length; j++) {
271 var item = dataset[j];
272 var xValue = DygraphLayout.parseFloat_(item[0]);
273 var yValue = DygraphLayout.parseFloat_(item[1]);
274
275 // Range from 0-1 where 0 represents left and 1 represents right.
276 var xNormal = (xValue - this.minxval) * this.xscale;
277 // Range from 0-1 where 0 represents top and 1 represents bottom
278 var yNormal = DygraphLayout._calcYNormal(axis, yValue);
279
280 if (connectSeparated && item[1] === null) {
281 yValue = null;
282 }
283 this.points[i] = {
284 // TODO(danvk): here
285 x: xNormal,
286 y: yNormal,
287 xval: xValue,
288 yval: yValue,
289 name: setName
290 };
291 i++;
292 }
293 this.setPointsLengths.push(i - this.setPointsOffsets[setIdx]);
294 }
295 };
296
297 /**
298 * Optimized replacement for parseFloat, which was way too slow when almost
299 * all values were type number, with few edge cases, none of which were strings.
300 */
301 DygraphLayout.parseFloat_ = function(val) {
302 // parseFloat(null) is NaN
303 if (val === null) {
304 return NaN;
305 }
306
307 // Assume it's a number or NaN. If it's something else, I'll be shocked.
308 return val;
309 }
310
311 DygraphLayout.prototype._evaluateLineTicks = function() {
312 var i, tick, label, pos;
313 this.xticks = [];
314 for (i = 0; i < this.xTicks_.length; i++) {
315 tick = this.xTicks_[i];
316 label = tick.label;
317 pos = this.xscale * (tick.v - this.minxval);
318 if ((pos >= 0.0) && (pos <= 1.0)) {
319 this.xticks.push([pos, label]);
320 }
321 }
322
323 this.yticks = [];
324 for (i = 0; i < this.yAxes_.length; i++ ) {
325 var axis = this.yAxes_[i];
326 for (var j = 0; j < axis.ticks.length; j++) {
327 tick = axis.ticks[j];
328 label = tick.label;
329 pos = this.dygraph_.toPercentYCoord(tick.v, i);
330 if ((pos >= 0.0) && (pos <= 1.0)) {
331 this.yticks.push([i, pos, label]);
332 }
333 }
334 }
335 };
336
337
338 /**
339 * Behaves the same way as PlotKit.Layout, but also copies the errors
340 * @private
341 */
342 DygraphLayout.prototype.evaluateWithError = function() {
343 this.evaluate();
344 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
345
346 // Copy over the error terms
347 var i = 0; // index in this.points
348 for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
349 var j = 0;
350 var dataset = this.datasets[setIdx];
351 var setName = this.setNames[setIdx];
352 var axis = this.dygraph_.axisPropertiesForSeries(setName);
353 for (j = 0; j < dataset.length; j++, i++) {
354 var item = dataset[j];
355 var xv = DygraphLayout.parseFloat_(item[0]);
356 var yv = DygraphLayout.parseFloat_(item[1]);
357
358 if (xv == this.points[i].xval &&
359 yv == this.points[i].yval) {
360 var errorMinus = DygraphLayout.parseFloat_(item[2]);
361 var errorPlus = DygraphLayout.parseFloat_(item[3]);
362
363 var yv_minus = yv - errorMinus;
364 var yv_plus = yv + errorPlus;
365 this.points[i].y_top = DygraphLayout._calcYNormal(axis, yv_minus);
366 this.points[i].y_bottom = DygraphLayout._calcYNormal(axis, yv_plus);
367 }
368 }
369 }
370 };
371
372 DygraphLayout.prototype._evaluateAnnotations = function() {
373 // Add the annotations to the point to which they belong.
374 // Make a map from (setName, xval) to annotation for quick lookups.
375 var i;
376 var annotations = {};
377 for (i = 0; i < this.annotations.length; i++) {
378 var a = this.annotations[i];
379 annotations[a.xval + "," + a.series] = a;
380 }
381
382 this.annotated_points = [];
383
384 // Exit the function early if there are no annotations.
385 if (!this.annotations || !this.annotations.length) {
386 return;
387 }
388
389 // TODO(antrob): loop through annotations not points.
390 for (i = 0; i < this.points.length; i++) {
391 var p = this.points[i];
392 var k = p.xval + "," + p.name;
393 if (k in annotations) {
394 p.annotation = annotations[k];
395 this.annotated_points.push(p);
396 }
397 }
398 };
399
400 /**
401 * Convenience function to remove all the data sets from a graph
402 */
403 DygraphLayout.prototype.removeAllDatasets = function() {
404 delete this.datasets;
405 delete this.setNames;
406 delete this.setPointsLengths;
407 delete this.setPointsOffsets;
408 this.datasets = [];
409 this.setNames = [];
410 this.setPointsLengths = [];
411 this.setPointsOffsets = [];
412 };
413
414 /**
415 * Return a copy of the point at the indicated index, with its yval unstacked.
416 * @param int index of point in layout_.points
417 */
418 DygraphLayout.prototype.unstackPointAtIndex = function(idx) {
419 var point = this.points[idx];
420 // If the point is missing, no unstacking is necessary
421 if (!point.yval) {
422 return point;
423 }
424
425 // Clone the point since we modify it
426 var unstackedPoint = {};
427 for (var pt in point) {
428 unstackedPoint[pt] = point[pt];
429 }
430
431 if (!this.attr_("stackedGraph")) {
432 return unstackedPoint;
433 }
434
435 // The unstacked yval is equal to the current yval minus the yval of the
436 // next point at the same xval.
437 for (var i = idx+1; i < this.points.length; i++) {
438 if ((this.points[i].xval == point.xval) && this.points[i].yval) {
439 unstackedPoint.yval -= this.points[i].yval;
440 break;
441 }
442 }
443
444 return unstackedPoint;
445 };