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