start y-label port; not working yet
[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 };
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_;
6dca682f
DV
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
ccd9d7c2
PF
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
6dca682f 121/*
ccd9d7c2
PF
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
d0c39108
DV
137 if (this.attr_('y2label')) {
138 // same logic applies here as for ylabel.
139 // TODO(danvk): make yAxisLabelWidth a per-axis property
140 }
6dca682f 141*/
d0c39108 142
ccd9d7c2
PF
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
74a5af31
DV
151DygraphLayout.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
175DygraphLayout.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.
180DygraphLayout.prototype.setYAxes = function (yAxes) {
181 this.yAxes_ = yAxes;
182};
183
184DygraphLayout.prototype.setDateWindow = function(dateWindow) {
185 this.dateWindow_ = dateWindow;
186};
187
188DygraphLayout.prototype.evaluate = function() {
189 this._evaluateLimits();
190 this._evaluateLineCharts();
191 this._evaluateLineTicks();
192 this._evaluateAnnotations();
193};
194
195DygraphLayout.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 {
82c6fe4d
KW
201 for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
202 var series = this.datasets[setIdx];
74a5af31
DV
203 if (series.length > 1) {
204 var x1 = series[0][0];
205 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
ccd9d7c2 206
74a5af31
DV
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;
758a629f 213 this.xscale = (this.xrange !== 0 ? 1/this.xrange : 1.0);
74a5af31
DV
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;
758a629f 220 axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);
74a5af31
DV
221
222 if (axis.g.attr_("logscale")) {
223 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
758a629f 224 axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
74a5af31
DV
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
7f028980
DV
234DygraphLayout._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
74a5af31 242DygraphLayout.prototype._evaluateLineCharts = function() {
c3e1495b
AR
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
fc77253b
DV
245 // for every data set since the points are added in order of the sets in
246 // datasets.
758a629f 247 this.setPointsLengths = [];
82c6fe4d 248 this.setPointsOffsets = [];
c3e1495b 249
04c104d7 250 var connectSeparated = this.attr_('connectSeparatedPoints');
b843b52c
RK
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;
57915b7a 256 var setIdx;
99a77a04
RK
257
258 // Preallocating the size of points reduces reallocations, and therefore,
259 // calls to collect garbage.
b843b52c 260 var totalPoints = 0;
57915b7a 261 for (setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
b843b52c
RK
262 totalPoints += this.datasets[setIdx].length;
263 }
264 this.points = new Array(totalPoints);
265
57915b7a 266 for (setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
b843b52c 267 this.setPointsOffsets.push(i);
82c6fe4d
KW
268 var dataset = this.datasets[setIdx];
269 var setName = this.setNames[setIdx];
74a5af31
DV
270 var axis = this.dygraph_.axisPropertiesForSeries(setName);
271
272 for (var j = 0; j < dataset.length; j++) {
273 var item = dataset[j];
57915b7a
RK
274 var xValue = DygraphLayout.parseFloat_(item[0]);
275 var yValue = DygraphLayout.parseFloat_(item[1]);
ecf9b464 276
4ab8db0c 277 // Range from 0-1 where 0 represents left and 1 represents right.
7f028980
DV
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
57915b7a 282 if (connectSeparated && item[1] === null) {
b843b52c
RK
283 yValue = null;
284 }
285 this.points[i] = {
f9414b11
DV
286 // TODO(danvk): here
287 x: xNormal,
288 y: yNormal,
289 xval: xValue,
290 yval: yValue,
291 name: setName
292 };
b843b52c 293 i++;
74a5af31 294 }
b843b52c 295 this.setPointsLengths.push(i - this.setPointsOffsets[setIdx]);
74a5af31
DV
296 }
297};
298
57915b7a
RK
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 */
303DygraphLayout.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
74a5af31 313DygraphLayout.prototype._evaluateLineTicks = function() {
758a629f
DV
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);
74a5af31
DV
320 if ((pos >= 0.0) && (pos <= 1.0)) {
321 this.xticks.push([pos, label]);
322 }
323 }
324
758a629f
DV
325 this.yticks = [];
326 for (i = 0; i < this.yAxes_.length; i++ ) {
74a5af31
DV
327 var axis = this.yAxes_[i];
328 for (var j = 0; j < axis.ticks.length; j++) {
758a629f
DV
329 tick = axis.ticks[j];
330 label = tick.label;
331 pos = this.dygraph_.toPercentYCoord(tick.v, i);
74a5af31
DV
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 */
344DygraphLayout.prototype.evaluateWithError = function() {
345 this.evaluate();
346 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
347
348 // Copy over the error terms
758a629f 349 var i = 0; // index in this.points
82c6fe4d 350 for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
74a5af31 351 var j = 0;
82c6fe4d
KW
352 var dataset = this.datasets[setIdx];
353 var setName = this.setNames[setIdx];
7f028980 354 var axis = this.dygraph_.axisPropertiesForSeries(setName);
758a629f 355 for (j = 0; j < dataset.length; j++, i++) {
74a5af31 356 var item = dataset[j];
57915b7a
RK
357 var xv = DygraphLayout.parseFloat_(item[0]);
358 var yv = DygraphLayout.parseFloat_(item[1]);
74a5af31
DV
359
360 if (xv == this.points[i].xval &&
361 yv == this.points[i].yval) {
57915b7a
RK
362 var errorMinus = DygraphLayout.parseFloat_(item[2]);
363 var errorPlus = DygraphLayout.parseFloat_(item[3]);
7f028980
DV
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);
74a5af31
DV
369 }
370 }
371 }
372};
373
374DygraphLayout.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.
758a629f 377 var i;
74a5af31 378 var annotations = {};
758a629f 379 for (i = 0; i < this.annotations.length; i++) {
74a5af31
DV
380 var a = this.annotations[i];
381 annotations[a.xval + "," + a.series] = a;
382 }
383
384 this.annotated_points = [];
d570a072
AR
385
386 // Exit the function early if there are no annotations.
387 if (!this.annotations || !this.annotations.length) {
388 return;
389 }
ccd9d7c2 390
d570a072 391 // TODO(antrob): loop through annotations not points.
758a629f 392 for (i = 0; i < this.points.length; i++) {
74a5af31
DV
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 */
405DygraphLayout.prototype.removeAllDatasets = function() {
406 delete this.datasets;
82c6fe4d
KW
407 delete this.setNames;
408 delete this.setPointsLengths;
409 delete this.setPointsOffsets;
758a629f 410 this.datasets = [];
82c6fe4d
KW
411 this.setNames = [];
412 this.setPointsLengths = [];
413 this.setPointsOffsets = [];
74a5af31
DV
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 */
420DygraphLayout.prototype.unstackPointAtIndex = function(idx) {
421 var point = this.points[idx];
52ca2280 422 // If the point is missing, no unstacking is necessary
c6bdcd60
AV
423 if (!point.yval) {
424 return point;
425 }
ccd9d7c2 426
74a5af31 427 // Clone the point since we modify it
ccd9d7c2 428 var unstackedPoint = {};
758a629f
DV
429 for (var pt in point) {
430 unstackedPoint[pt] = point[pt];
74a5af31 431 }
ccd9d7c2 432
74a5af31
DV
433 if (!this.attr_("stackedGraph")) {
434 return unstackedPoint;
435 }
ccd9d7c2
PF
436
437 // The unstacked yval is equal to the current yval minus the yval of the
74a5af31
DV
438 // next point at the same xval.
439 for (var i = idx+1; i < this.points.length; i++) {
c6bdcd60 440 if ((this.points[i].xval == point.xval) && this.points[i].yval) {
ccd9d7c2 441 unstackedPoint.yval -= this.points[i].yval;
74a5af31
DV
442 break;
443 }
444 }
ccd9d7c2 445
74a5af31 446 return unstackedPoint;
758a629f 447};