Merge branch 'master' of github.com:danvk/dygraphs into closure
[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 this.points = null;
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
46 DygraphLayout.prototype.attr_ = function(name) {
47 return this.dygraph_.attr_(name);
48 };
49
50 DygraphLayout.prototype.addDataset = function(setname, set_xy) {
51 this.datasets.push(set_xy);
52 this.setNames.push(setname);
53 };
54
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 : numer, y : number, w : number, h : number }}
60 */
61 DygraphLayout.prototype.getPlotArea = function() {
62 return this.area_;
63 };
64
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.
67 // NOTE: This should only be called by Dygraph.predraw_().
68 DygraphLayout.prototype.computePlotArea = function() {
69 var area = {
70 // TODO(danvk): per-axis setting.
71 x: 0,
72 y: 0
73 };
74
75 area.w = this.dygraph_.width_ - area.x - this.attr_('rightGap');
76 area.h = this.dygraph_.height_;
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 },
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 },
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 },
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 },
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
129 this.area_ = area;
130 };
131
132 DygraphLayout.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 = {};
139 if (!ann[i].xval && ann[i].x === undefined) {
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
156 DygraphLayout.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.
161 DygraphLayout.prototype.setYAxes = function (yAxes) {
162 this.yAxes_ = yAxes;
163 };
164
165 DygraphLayout.prototype.setDateWindow = function(dateWindow) {
166 this.dateWindow_ = dateWindow;
167 };
168
169 DygraphLayout.prototype.evaluate = function() {
170 this._evaluateLimits();
171 this._evaluateLineCharts();
172 this._evaluateLineTicks();
173 this._evaluateAnnotations();
174 };
175
176 DygraphLayout.prototype._evaluateLimits = function() {
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);
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;
188 axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);
189
190 if (axis.g.attr_("logscale")) {
191 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
192 axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
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
202 DygraphLayout._calcYNormal = function(axis, value, logscale) {
203 if (logscale) {
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
210 DygraphLayout.prototype._evaluateLineCharts = function() {
211 var connectSeparated = this.attr_('connectSeparatedPoints');
212
213 // series index -> point index in series -> |point| structure
214 this.points = new Array(this.datasets.length);
215
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.
220 var boundaryIdStart = 0;
221 if (this.dygraph_.boundaryIds_.length > 0) {
222 boundaryIdStart = this.dygraph_.boundaryIds_[this.dygraph_.boundaryIds_.length-1][0]
223 }
224 for (var setIdx = 0; setIdx < this.datasets.length; setIdx++) {
225 var dataset = this.datasets[setIdx];
226 var setName = this.setNames[setIdx];
227 var axis = this.dygraph_.axisPropertiesForSeries(setName);
228 // TODO (konigsberg): use optionsForAxis instead.
229 var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName);
230
231 // Preallocating the size of points reduces reallocations, and therefore,
232 // calls to collect garbage.
233 var seriesPoints = new Array(dataset.length);
234
235 for (var j = 0; j < dataset.length; j++) {
236 var item = dataset[j];
237 var xValue = DygraphLayout.parseFloat_(item[0]);
238 var yValue = DygraphLayout.parseFloat_(item[1]);
239
240 // Range from 0-1 where 0 represents left and 1 represents right.
241 var xNormal = (xValue - this.minxval) * this.xscale;
242 // Range from 0-1 where 0 represents top and 1 represents bottom
243 var yNormal = DygraphLayout._calcYNormal(axis, yValue, logscale);
244
245 // TODO(danvk): drop the point in this case, don't null it.
246 // The nulls create complexity in DygraphCanvasRenderer._drawSeries.
247 if (connectSeparated && item[1] === null) {
248 yValue = null;
249 }
250 seriesPoints[j] = {
251 x: xNormal,
252 y: yNormal,
253 xval: xValue,
254 yval: yValue,
255 name: setName, // TODO(danvk): is this really necessary?
256 idx: j + boundaryIdStart
257 };
258 }
259
260 this.points[setIdx] = seriesPoints;
261 }
262 };
263
264 /**
265 * Optimized replacement for parseFloat, which was way too slow when almost
266 * all values were type number, with few edge cases, none of which were strings.
267 */
268 DygraphLayout.parseFloat_ = function(val) {
269 // parseFloat(null) is NaN
270 if (val === null) {
271 return NaN;
272 }
273
274 // Assume it's a number or NaN. If it's something else, I'll be shocked.
275 return val;
276 };
277
278 DygraphLayout.prototype._evaluateLineTicks = function() {
279 var i, tick, label, pos;
280 this.xticks = [];
281 for (i = 0; i < this.xTicks_.length; i++) {
282 tick = this.xTicks_[i];
283 label = tick.label;
284 pos = this.xscale * (tick.v - this.minxval);
285 if ((pos >= 0.0) && (pos <= 1.0)) {
286 this.xticks.push([pos, label]);
287 }
288 }
289
290 this.yticks = [];
291 for (i = 0; i < this.yAxes_.length; i++ ) {
292 var axis = this.yAxes_[i];
293 for (var j = 0; j < axis.ticks.length; j++) {
294 tick = axis.ticks[j];
295 label = tick.label;
296 pos = this.dygraph_.toPercentYCoord(tick.v, i);
297 if ((pos >= 0.0) && (pos <= 1.0)) {
298 this.yticks.push([i, pos, label]);
299 }
300 }
301 }
302 };
303
304
305 /**
306 * Behaves the same way as PlotKit.Layout, but also copies the errors
307 * @private
308 */
309 DygraphLayout.prototype.evaluateWithError = function() {
310 this.evaluate();
311 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
312
313 // Copy over the error terms
314 var i = 0; // index in this.points
315 for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
316 var points = this.points[setIdx];
317 var j = 0;
318 var dataset = this.datasets[setIdx];
319 var setName = this.setNames[setIdx];
320 var axis = this.dygraph_.axisPropertiesForSeries(setName);
321 // TODO (konigsberg): use optionsForAxis instead.
322 var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName);
323
324 for (j = 0; j < dataset.length; j++, i++) {
325 var item = dataset[j];
326 var xv = DygraphLayout.parseFloat_(item[0]);
327 var yv = DygraphLayout.parseFloat_(item[1]);
328
329 if (xv == points[j].xval &&
330 yv == points[j].yval) {
331 var errorMinus = DygraphLayout.parseFloat_(item[2]);
332 var errorPlus = DygraphLayout.parseFloat_(item[3]);
333
334 var yv_minus = yv - errorMinus;
335 var yv_plus = yv + errorPlus;
336 points[j].y_top = DygraphLayout._calcYNormal(axis, yv_minus, logscale);
337 points[j].y_bottom = DygraphLayout._calcYNormal(axis, yv_plus, logscale);
338 }
339 }
340 }
341 };
342
343 DygraphLayout.prototype._evaluateAnnotations = function() {
344 // Add the annotations to the point to which they belong.
345 // Make a map from (setName, xval) to annotation for quick lookups.
346 var i;
347 var annotations = {};
348 for (i = 0; i < this.annotations.length; i++) {
349 var a = this.annotations[i];
350 annotations[a.xval + "," + a.series] = a;
351 }
352
353 this.annotated_points = [];
354
355 // Exit the function early if there are no annotations.
356 if (!this.annotations || !this.annotations.length) {
357 return;
358 }
359
360 // TODO(antrob): loop through annotations not points.
361 for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
362 var points = this.points[setIdx];
363 for (i = 0; i < points.length; i++) {
364 var p = points[i];
365 var k = p.xval + "," + p.name;
366 if (k in annotations) {
367 p.annotation = annotations[k];
368 this.annotated_points.push(p);
369 }
370 }
371 }
372 };
373
374 /**
375 * Convenience function to remove all the data sets from a graph
376 */
377 DygraphLayout.prototype.removeAllDatasets = function() {
378 delete this.datasets;
379 delete this.setNames;
380 delete this.setPointsLengths;
381 delete this.setPointsOffsets;
382 this.datasets = [];
383 this.setNames = [];
384 this.setPointsLengths = [];
385 this.setPointsOffsets = [];
386 };
387
388 /**
389 * Return a copy of the point at the indicated index, with its yval unstacked.
390 * @param int index of point in layout_.points
391 */
392 DygraphLayout.prototype.unstackPointAtIndex = function(setIdx, row) {
393 var point = this.points[setIdx][row];
394 // If the point is missing, no unstacking is necessary
395 if (!Dygraph.isValidPoint(point)) {
396 return point;
397 }
398
399 // Clone the point since we modify it
400 var unstackedPoint = {};
401 for (var pt in point) {
402 unstackedPoint[pt] = point[pt];
403 }
404
405 if (!this.attr_("stackedGraph")) {
406 return unstackedPoint;
407 }
408
409 // The unstacked yval is equal to the current yval minus the yval of the
410 // next point at the same xval.
411 // We need to iterate over setIdx just in case some series have invalid values
412 // at current row
413 for(setIdx++; setIdx < this.points.length; setIdx++) {
414 var nextPoint = this.points[setIdx][row];
415 if (nextPoint.xval == point.xval && // should always be true?
416 Dygraph.isValidPoint(nextPoint)) {
417 unstackedPoint.yval -= nextPoint.yval;
418 break; // stop at first valid point
419 }
420 }
421
422 return unstackedPoint;
423 };