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