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