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