add comment explaining isFinite check
[dygraphs.git] / dygraph-layout.js
... / ...
CommitLineData
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 */
32var DygraphLayout = function(dygraph) {
33 this.dygraph_ = dygraph;
34 /**
35 * Array of points for each series.
36 *
37 * [series index][row index in series] = |Point| structure,
38 * where series index refers to visible series only, and the
39 * point index is for the reduced set of points for the current
40 * zoom region (including one point just outside the window).
41 * All points in the same row index share the same X value.
42 *
43 * @type {Array.<Array.<Dygraph.PointType>>}
44 */
45 this.points = [];
46 this.setNames = [];
47 this.annotations = [];
48 this.yAxes_ = null;
49
50 // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
51 // yticks are outputs. Clean this up.
52 this.xTicks_ = null;
53 this.yTicks_ = null;
54};
55
56DygraphLayout.prototype.attr_ = function(name) {
57 return this.dygraph_.attr_(name);
58};
59
60/**
61 * Add points for a single series.
62 *
63 * @param {string} setname Name of the series.
64 * @param {Array.<Dygraph.PointType>} set_xy Points for the series.
65 */
66DygraphLayout.prototype.addDataset = function(setname, set_xy) {
67 this.points.push(set_xy);
68 this.setNames.push(setname);
69};
70
71/**
72 * Returns the box which the chart should be drawn in. This is the canvas's
73 * box, less space needed for the axis and chart labels.
74 *
75 * @return {{x: number, y: number, w: number, h: number}}
76 */
77DygraphLayout.prototype.getPlotArea = function() {
78 return this.area_;
79};
80
81// Compute the box which the chart should be drawn in. This is the canvas's
82// box, less space needed for axis, chart labels, and other plug-ins.
83// NOTE: This should only be called by Dygraph.predraw_().
84DygraphLayout.prototype.computePlotArea = function() {
85 var area = {
86 // TODO(danvk): per-axis setting.
87 x: 0,
88 y: 0
89 };
90
91 area.w = this.dygraph_.width_ - area.x - this.attr_('rightGap');
92 area.h = this.dygraph_.height_;
93
94 // Let plugins reserve space.
95 var e = {
96 chart_div: this.dygraph_.graphDiv,
97 reserveSpaceLeft: function(px) {
98 var r = {
99 x: area.x,
100 y: area.y,
101 w: px,
102 h: area.h
103 };
104 area.x += px;
105 area.w -= px;
106 return r;
107 },
108 reserveSpaceRight: function(px) {
109 var r = {
110 x: area.x + area.w - px,
111 y: area.y,
112 w: px,
113 h: area.h
114 };
115 area.w -= px;
116 return r;
117 },
118 reserveSpaceTop: function(px) {
119 var r = {
120 x: area.x,
121 y: area.y,
122 w: area.w,
123 h: px
124 };
125 area.y += px;
126 area.h -= px;
127 return r;
128 },
129 reserveSpaceBottom: function(px) {
130 var r = {
131 x: area.x,
132 y: area.y + area.h - px,
133 w: area.w,
134 h: px
135 };
136 area.h -= px;
137 return r;
138 },
139 chartRect: function() {
140 return {x:area.x, y:area.y, w:area.w, h:area.h};
141 }
142 };
143 this.dygraph_.cascadeEvents_('layout', e);
144
145 this.area_ = area;
146};
147
148DygraphLayout.prototype.setAnnotations = function(ann) {
149 // The Dygraph object's annotations aren't parsed. We parse them here and
150 // save a copy. If there is no parser, then the user must be using raw format.
151 this.annotations = [];
152 var parse = this.attr_('xValueParser') || function(x) { return x; };
153 for (var i = 0; i < ann.length; i++) {
154 var a = {};
155 if (!ann[i].xval && ann[i].x === undefined) {
156 this.dygraph_.error("Annotations must have an 'x' property");
157 return;
158 }
159 if (ann[i].icon &&
160 !(ann[i].hasOwnProperty('width') &&
161 ann[i].hasOwnProperty('height'))) {
162 this.dygraph_.error("Must set width and height when setting " +
163 "annotation.icon property");
164 return;
165 }
166 Dygraph.update(a, ann[i]);
167 if (!a.xval) a.xval = parse(a.x);
168 this.annotations.push(a);
169 }
170};
171
172DygraphLayout.prototype.setXTicks = function(xTicks) {
173 this.xTicks_ = xTicks;
174};
175
176// TODO(danvk): add this to the Dygraph object's API or move it into Layout.
177DygraphLayout.prototype.setYAxes = function (yAxes) {
178 this.yAxes_ = yAxes;
179};
180
181DygraphLayout.prototype.evaluate = function() {
182 this._evaluateLimits();
183 this._evaluateLineCharts();
184 this._evaluateLineTicks();
185 this._evaluateAnnotations();
186};
187
188DygraphLayout.prototype._evaluateLimits = function() {
189 var xlimits = this.dygraph_.xAxisRange();
190 this.minxval = xlimits[0];
191 this.maxxval = xlimits[1];
192 var xrange = xlimits[1] - xlimits[0];
193 this.xscale = (xrange !== 0 ? 1 / xrange : 1.0);
194
195 for (var i = 0; i < this.yAxes_.length; i++) {
196 var axis = this.yAxes_[i];
197 axis.minyval = axis.computedValueRange[0];
198 axis.maxyval = axis.computedValueRange[1];
199 axis.yrange = axis.maxyval - axis.minyval;
200 axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);
201
202 if (axis.g.attr_("logscale")) {
203 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
204 axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
205 if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
206 axis.g.error('axis ' + i + ' of graph at ' + axis.g +
207 ' can\'t be displayed in log scale for range [' +
208 axis.minyval + ' - ' + axis.maxyval + ']');
209 }
210 }
211 }
212};
213
214DygraphLayout._calcYNormal = function(axis, value, logscale) {
215 if (logscale) {
216 var x = 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale);
217 return isFinite(x) ? x : NaN; // shim for v8 issue; see pull request 276
218 } else {
219 return 1.0 - ((value - axis.minyval) * axis.yscale);
220 }
221};
222
223DygraphLayout.prototype._evaluateLineCharts = function() {
224 var connectSeparated = this.attr_('connectSeparatedPoints');
225 var isStacked = this.attr_("stackedGraph");
226
227 for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
228 var points = this.points[setIdx];
229 var setName = this.setNames[setIdx];
230 var axis = this.dygraph_.axisPropertiesForSeries(setName);
231 // TODO (konigsberg): use optionsForAxis instead.
232 var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName);
233
234 for (var j = 0; j < points.length; j++) {
235 var point = points[j];
236
237 // Range from 0-1 where 0 represents left and 1 represents right.
238 point.x = (point.xval - this.minxval) * this.xscale;
239 // Range from 0-1 where 0 represents top and 1 represents bottom
240 var yval = point.yval;
241 if (isStacked) {
242 point.y_stacked = DygraphLayout._calcYNormal(
243 axis, point.yval_stacked, logscale);
244 if (yval !== null && !isNaN(yval)) {
245 yval = point.yval_stacked;
246 }
247 }
248 if (yval === null) {
249 yval = NaN;
250 if (!connectSeparated) {
251 point.yval = NaN;
252 }
253 }
254 point.y = DygraphLayout._calcYNormal(axis, yval, logscale);
255 }
256
257 this.dygraph_.dataHandler_.onLineEvaluated(points, axis, logscale);
258 }
259};
260
261/**
262 * Optimized replacement for parseFloat, which was way too slow when almost
263 * all values were type number, with few edge cases, none of which were strings.
264 */
265DygraphLayout.parseFloat_ = function(val) {
266 // parseFloat(null) is NaN
267 if (val === null) {
268 return NaN;
269 }
270
271 // Assume it's a number or NaN. If it's something else, I'll be shocked.
272 return val;
273};
274
275DygraphLayout.prototype._evaluateLineTicks = function() {
276 var i, tick, label, pos;
277 this.xticks = [];
278 for (i = 0; i < this.xTicks_.length; i++) {
279 tick = this.xTicks_[i];
280 label = tick.label;
281 pos = this.xscale * (tick.v - this.minxval);
282 if ((pos >= 0.0) && (pos < 1.0)) {
283 this.xticks.push([pos, label]);
284 }
285 }
286
287 this.yticks = [];
288 for (i = 0; i < this.yAxes_.length; i++ ) {
289 var axis = this.yAxes_[i];
290 for (var j = 0; j < axis.ticks.length; j++) {
291 tick = axis.ticks[j];
292 label = tick.label;
293 pos = this.dygraph_.toPercentYCoord(tick.v, i);
294 if ((pos > 0.0) && (pos <= 1.0)) {
295 this.yticks.push([i, pos, label]);
296 }
297 }
298 }
299};
300
301DygraphLayout.prototype._evaluateAnnotations = function() {
302 // Add the annotations to the point to which they belong.
303 // Make a map from (setName, xval) to annotation for quick lookups.
304 var i;
305 var annotations = {};
306 for (i = 0; i < this.annotations.length; i++) {
307 var a = this.annotations[i];
308 annotations[a.xval + "," + a.series] = a;
309 }
310
311 this.annotated_points = [];
312
313 // Exit the function early if there are no annotations.
314 if (!this.annotations || !this.annotations.length) {
315 return;
316 }
317
318 // TODO(antrob): loop through annotations not points.
319 for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
320 var points = this.points[setIdx];
321 for (i = 0; i < points.length; i++) {
322 var p = points[i];
323 var k = p.xval + "," + p.name;
324 if (k in annotations) {
325 p.annotation = annotations[k];
326 this.annotated_points.push(p);
327 }
328 }
329 }
330};
331
332/**
333 * Convenience function to remove all the data sets from a graph
334 */
335DygraphLayout.prototype.removeAllDatasets = function() {
336 delete this.points;
337 delete this.setNames;
338 delete this.setPointsLengths;
339 delete this.setPointsOffsets;
340 this.points = [];
341 this.setNames = [];
342 this.setPointsLengths = [];
343 this.setPointsOffsets = [];
344};