Add drawAxis option, deprecating drawXAxis and drawYAxis. Added tests for that and...
[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;
30a5cfc6
KW
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 = [];
82c6fe4d 46 this.setNames = [];
758a629f 47 this.annotations = [];
74a5af31
DV
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
30a5cfc6
KW
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 */
74a5af31 66DygraphLayout.prototype.addDataset = function(setname, set_xy) {
30a5cfc6 67 this.points.push(set_xy);
82c6fe4d 68 this.setNames.push(setname);
74a5af31
DV
69};
70
141064ff
DE
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 */
70be5ed1 77DygraphLayout.prototype.getPlotArea = function() {
0d216a60 78 return this.area_;
758a629f 79};
70be5ed1 80
ccd9d7c2 81// Compute the box which the chart should be drawn in. This is the canvas's
ad617f17 82// box, less space needed for axis, chart labels, and other plug-ins.
ec475f44 83// NOTE: This should only be called by Dygraph.predraw_().
0d216a60 84DygraphLayout.prototype.computePlotArea = function() {
ccd9d7c2
PF
85 var area = {
86 // TODO(danvk): per-axis setting.
87 x: 0,
88 y: 0
89 };
f8540c66 90
ccd9d7c2
PF
91 area.w = this.dygraph_.width_ - area.x - this.attr_('rightGap');
92 area.h = this.dygraph_.height_;
6dca682f
DV
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 },
1c177b6a
DV
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 },
6dca682f
DV
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 },
1c177b6a
DV
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 },
6dca682f
DV
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
0d216a60 145 this.area_ = area;
ccd9d7c2
PF
146};
147
74a5af31
DV
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 = {};
b5481aea 155 if (!ann[i].xval && ann[i].x === undefined) {
74a5af31
DV
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
74a5af31
DV
181DygraphLayout.prototype.evaluate = function() {
182 this._evaluateLimits();
183 this._evaluateLineCharts();
184 this._evaluateLineTicks();
185 this._evaluateAnnotations();
186};
187
188DygraphLayout.prototype._evaluateLimits = function() {
fa460473
KW
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);
74a5af31
DV
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;
758a629f 200 axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);
74a5af31
DV
201
202 if (axis.g.attr_("logscale")) {
203 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
758a629f 204 axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
74a5af31
DV
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
23db4e07
RK
214DygraphLayout._calcYNormal = function(axis, value, logscale) {
215 if (logscale) {
7f028980
DV
216 return 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale);
217 } else {
218 return 1.0 - ((value - axis.minyval) * axis.yscale);
219 }
220};
221
74a5af31 222DygraphLayout.prototype._evaluateLineCharts = function() {
04c104d7 223 var connectSeparated = this.attr_('connectSeparatedPoints');
30a5cfc6 224 var isStacked = this.attr_("stackedGraph");
a12a78ae 225
30a5cfc6
KW
226 for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
227 var points = this.points[setIdx];
82c6fe4d 228 var setName = this.setNames[setIdx];
74a5af31 229 var axis = this.dygraph_.axisPropertiesForSeries(setName);
23db4e07 230 // TODO (konigsberg): use optionsForAxis instead.
8e19509a 231 var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName);
74a5af31 232
30a5cfc6
KW
233 for (var j = 0; j < points.length; j++) {
234 var point = points[j];
ecf9b464 235
4ab8db0c 236 // Range from 0-1 where 0 represents left and 1 represents right.
30a5cfc6 237 point.x = (point.xval - this.minxval) * this.xscale;
7f028980 238 // Range from 0-1 where 0 represents top and 1 represents bottom
30a5cfc6
KW
239 var yval = point.yval;
240 if (isStacked) {
241 point.y_stacked = DygraphLayout._calcYNormal(
242 axis, point.yval_stacked, logscale);
243 if (yval !== null && !isNaN(yval)) {
244 yval = point.yval_stacked;
245 }
246 }
247 if (yval === null) {
248 yval = NaN;
249 if (!connectSeparated) {
250 point.yval = NaN;
251 }
252 }
253 point.y = DygraphLayout._calcYNormal(axis, yval, logscale);
74a5af31 254 }
a49c164a
DE
255
256 this.dygraph_.dataHandler_.onLineEvaluated(points, axis, logscale);
74a5af31
DV
257 }
258};
259
57915b7a
RK
260/**
261 * Optimized replacement for parseFloat, which was way too slow when almost
262 * all values were type number, with few edge cases, none of which were strings.
263 */
264DygraphLayout.parseFloat_ = function(val) {
265 // parseFloat(null) is NaN
266 if (val === null) {
267 return NaN;
268 }
269
270 // Assume it's a number or NaN. If it's something else, I'll be shocked.
271 return val;
42a9ebb8 272};
57915b7a 273
74a5af31 274DygraphLayout.prototype._evaluateLineTicks = function() {
758a629f
DV
275 var i, tick, label, pos;
276 this.xticks = [];
277 for (i = 0; i < this.xTicks_.length; i++) {
278 tick = this.xTicks_[i];
279 label = tick.label;
280 pos = this.xscale * (tick.v - this.minxval);
74a5af31
DV
281 if ((pos >= 0.0) && (pos <= 1.0)) {
282 this.xticks.push([pos, label]);
283 }
284 }
285
758a629f
DV
286 this.yticks = [];
287 for (i = 0; i < this.yAxes_.length; i++ ) {
74a5af31
DV
288 var axis = this.yAxes_[i];
289 for (var j = 0; j < axis.ticks.length; j++) {
758a629f
DV
290 tick = axis.ticks[j];
291 label = tick.label;
292 pos = this.dygraph_.toPercentYCoord(tick.v, i);
74a5af31
DV
293 if ((pos >= 0.0) && (pos <= 1.0)) {
294 this.yticks.push([i, pos, label]);
295 }
296 }
297 }
298};
299
74a5af31
DV
300DygraphLayout.prototype._evaluateAnnotations = function() {
301 // Add the annotations to the point to which they belong.
302 // Make a map from (setName, xval) to annotation for quick lookups.
758a629f 303 var i;
74a5af31 304 var annotations = {};
758a629f 305 for (i = 0; i < this.annotations.length; i++) {
74a5af31
DV
306 var a = this.annotations[i];
307 annotations[a.xval + "," + a.series] = a;
308 }
309
310 this.annotated_points = [];
d570a072
AR
311
312 // Exit the function early if there are no annotations.
313 if (!this.annotations || !this.annotations.length) {
314 return;
315 }
ccd9d7c2 316
d570a072 317 // TODO(antrob): loop through annotations not points.
a12a78ae
DV
318 for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
319 var points = this.points[setIdx];
320 for (i = 0; i < points.length; i++) {
321 var p = points[i];
322 var k = p.xval + "," + p.name;
323 if (k in annotations) {
324 p.annotation = annotations[k];
325 this.annotated_points.push(p);
326 }
74a5af31
DV
327 }
328 }
329};
330
331/**
332 * Convenience function to remove all the data sets from a graph
333 */
334DygraphLayout.prototype.removeAllDatasets = function() {
30a5cfc6 335 delete this.points;
82c6fe4d
KW
336 delete this.setNames;
337 delete this.setPointsLengths;
338 delete this.setPointsOffsets;
30a5cfc6 339 this.points = [];
82c6fe4d
KW
340 this.setNames = [];
341 this.setPointsLengths = [];
342 this.setPointsOffsets = [];
74a5af31 343};