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