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