Add per-series 'color' option.
[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 /**
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
56 DygraphLayout.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 */
66 DygraphLayout.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 */
77 DygraphLayout.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_().
84 DygraphLayout.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
148 DygraphLayout.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
172 DygraphLayout.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.
177 DygraphLayout.prototype.setYAxes = function (yAxes) {
178 this.yAxes_ = yAxes;
179 };
180
181 DygraphLayout.prototype.evaluate = function() {
182 this._evaluateLimits();
183 this._evaluateLineCharts();
184 this._evaluateLineTicks();
185 this._evaluateAnnotations();
186 };
187
188 DygraphLayout.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
214 DygraphLayout._calcYNormal = function(axis, value, logscale) {
215 if (logscale) {
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
222 DygraphLayout.prototype._evaluateLineCharts = function() {
223 var connectSeparated = this.attr_('connectSeparatedPoints');
224 var isStacked = this.attr_("stackedGraph");
225
226 for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
227 var points = this.points[setIdx];
228 var setName = this.setNames[setIdx];
229 var axis = this.dygraph_.axisPropertiesForSeries(setName);
230 // TODO (konigsberg): use optionsForAxis instead.
231 var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName);
232
233 for (var j = 0; j < points.length; j++) {
234 var point = points[j];
235
236 // Range from 0-1 where 0 represents left and 1 represents right.
237 point.x = (point.xval - this.minxval) * this.xscale;
238 // Range from 0-1 where 0 represents top and 1 represents bottom
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);
254 }
255
256 this.dygraph_.dataHandler_.onLineEvaluated(points, axis, logscale);
257 }
258 };
259
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 */
264 DygraphLayout.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;
272 };
273
274 DygraphLayout.prototype._evaluateLineTicks = function() {
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);
281 if ((pos >= 0.0) && (pos <= 1.0)) {
282 this.xticks.push([pos, label]);
283 }
284 }
285
286 this.yticks = [];
287 for (i = 0; i < this.yAxes_.length; i++ ) {
288 var axis = this.yAxes_[i];
289 for (var j = 0; j < axis.ticks.length; j++) {
290 tick = axis.ticks[j];
291 label = tick.label;
292 pos = this.dygraph_.toPercentYCoord(tick.v, i);
293 if ((pos >= 0.0) && (pos <= 1.0)) {
294 this.yticks.push([i, pos, label]);
295 }
296 }
297 }
298 };
299
300 DygraphLayout.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.
303 var i;
304 var annotations = {};
305 for (i = 0; i < this.annotations.length; i++) {
306 var a = this.annotations[i];
307 annotations[a.xval + "," + a.series] = a;
308 }
309
310 this.annotated_points = [];
311
312 // Exit the function early if there are no annotations.
313 if (!this.annotations || !this.annotations.length) {
314 return;
315 }
316
317 // TODO(antrob): loop through annotations not points.
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 }
327 }
328 }
329 };
330
331 /**
332 * Convenience function to remove all the data sets from a graph
333 */
334 DygraphLayout.prototype.removeAllDatasets = function() {
335 delete this.points;
336 delete this.setNames;
337 delete this.setPointsLengths;
338 delete this.setPointsOffsets;
339 this.points = [];
340 this.setNames = [];
341 this.setPointsLengths = [];
342 this.setPointsOffsets = [];
343 };