Add a simple Usage Gallery to the dygraphs home page.
[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
c0f54d4f
DV
12"use strict";
13
74a5af31
DV
14/**
15 * Creates a new DygraphLayout object.
16 *
17 * This class contains all the data to be charted.
18 * It uses data coordinates, but also records the chart range (in data
19 * coordinates) and hence is able to calculate percentage positions ('In this
20 * view, Point A lies 25% down the x-axis.')
21 *
22 * Two things that it does not do are:
23 * 1. Record pixel coordinates for anything.
24 * 2. (oddly) determine anything about the layout of chart elements.
25 *
26 * The naming is a vestige of Dygraph's original PlotKit roots.
27 *
28 * @constructor
29 */
c0f54d4f 30var DygraphLayout = function(dygraph) {
74a5af31
DV
31 this.dygraph_ = dygraph;
32 this.datasets = new Array();
33 this.annotations = new Array();
34 this.yAxes_ = null;
35
36 // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
37 // yticks are outputs. Clean this up.
38 this.xTicks_ = null;
39 this.yTicks_ = null;
40};
41
42DygraphLayout.prototype.attr_ = function(name) {
43 return this.dygraph_.attr_(name);
44};
45
46DygraphLayout.prototype.addDataset = function(setname, set_xy) {
47 this.datasets[setname] = set_xy;
48};
49
70be5ed1
AV
50DygraphLayout.prototype.getPlotArea = function() {
51 return this.computePlotArea_();
52}
53
ccd9d7c2
PF
54// Compute the box which the chart should be drawn in. This is the canvas's
55// box, less space needed for axis and chart labels.
56DygraphLayout.prototype.computePlotArea_ = function() {
57 var area = {
58 // TODO(danvk): per-axis setting.
59 x: 0,
60 y: 0
61 };
62 if (this.attr_('drawYAxis')) {
63 area.x = this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize');
64 }
65
66 area.w = this.dygraph_.width_ - area.x - this.attr_('rightGap');
67 area.h = this.dygraph_.height_;
68 if (this.attr_('drawXAxis')) {
69 if (this.attr_('xAxisHeight')) {
70 area.h -= this.attr_('xAxisHeight');
71 } else {
72 area.h -= this.attr_('axisLabelFontSize') + 2 * this.attr_('axisTickSize');
73 }
74 }
75
76 // Shrink the drawing area to accomodate additional y-axes.
77 if (this.dygraph_.numAxes() == 2) {
78 // TODO(danvk): per-axis setting.
79 area.w -= (this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize'));
80 } else if (this.dygraph_.numAxes() > 2) {
81 this.dygraph_.error("Only two y-axes are supported at this time. (Trying " +
82 "to use " + this.dygraph_.numAxes() + ")");
83 }
84
85 // Add space for chart labels: title, xlabel and ylabel.
86 if (this.attr_('title')) {
87 area.h -= this.attr_('titleHeight');
88 area.y += this.attr_('titleHeight');
89 }
90 if (this.attr_('xlabel')) {
91 area.h -= this.attr_('xLabelHeight');
92 }
93 if (this.attr_('ylabel')) {
94 // It would make sense to shift the chart here to make room for the y-axis
95 // label, but the default yAxisLabelWidth is large enough that this results
96 // in overly-padded charts. The y-axis label should fit fine. If it
97 // doesn't, the yAxisLabelWidth option can be increased.
98 }
99
100 // Add space for range selector, if needed.
101 if (this.attr_('showRangeSelector')) {
102 area.h -= this.attr_('rangeSelectorHeight') + 4;
103 }
104
105 return area;
106};
107
74a5af31
DV
108DygraphLayout.prototype.setAnnotations = function(ann) {
109 // The Dygraph object's annotations aren't parsed. We parse them here and
110 // save a copy. If there is no parser, then the user must be using raw format.
111 this.annotations = [];
112 var parse = this.attr_('xValueParser') || function(x) { return x; };
113 for (var i = 0; i < ann.length; i++) {
114 var a = {};
115 if (!ann[i].xval && !ann[i].x) {
116 this.dygraph_.error("Annotations must have an 'x' property");
117 return;
118 }
119 if (ann[i].icon &&
120 !(ann[i].hasOwnProperty('width') &&
121 ann[i].hasOwnProperty('height'))) {
122 this.dygraph_.error("Must set width and height when setting " +
123 "annotation.icon property");
124 return;
125 }
126 Dygraph.update(a, ann[i]);
127 if (!a.xval) a.xval = parse(a.x);
128 this.annotations.push(a);
129 }
130};
131
132DygraphLayout.prototype.setXTicks = function(xTicks) {
133 this.xTicks_ = xTicks;
134};
135
136// TODO(danvk): add this to the Dygraph object's API or move it into Layout.
137DygraphLayout.prototype.setYAxes = function (yAxes) {
138 this.yAxes_ = yAxes;
139};
140
141DygraphLayout.prototype.setDateWindow = function(dateWindow) {
142 this.dateWindow_ = dateWindow;
143};
144
145DygraphLayout.prototype.evaluate = function() {
146 this._evaluateLimits();
147 this._evaluateLineCharts();
148 this._evaluateLineTicks();
149 this._evaluateAnnotations();
150};
151
152DygraphLayout.prototype._evaluateLimits = function() {
153 this.minxval = this.maxxval = null;
154 if (this.dateWindow_) {
155 this.minxval = this.dateWindow_[0];
156 this.maxxval = this.dateWindow_[1];
157 } else {
158 for (var name in this.datasets) {
159 if (!this.datasets.hasOwnProperty(name)) continue;
160 var series = this.datasets[name];
161 if (series.length > 1) {
162 var x1 = series[0][0];
163 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
ccd9d7c2 164
74a5af31
DV
165 var x2 = series[series.length - 1][0];
166 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
167 }
168 }
169 }
170 this.xrange = this.maxxval - this.minxval;
171 this.xscale = (this.xrange != 0 ? 1/this.xrange : 1.0);
172
173 for (var i = 0; i < this.yAxes_.length; i++) {
174 var axis = this.yAxes_[i];
175 axis.minyval = axis.computedValueRange[0];
176 axis.maxyval = axis.computedValueRange[1];
177 axis.yrange = axis.maxyval - axis.minyval;
178 axis.yscale = (axis.yrange != 0 ? 1.0 / axis.yrange : 1.0);
179
180 if (axis.g.attr_("logscale")) {
181 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
182 axis.ylogscale = (axis.ylogrange != 0 ? 1.0 / axis.ylogrange : 1.0);
183 if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
184 axis.g.error('axis ' + i + ' of graph at ' + axis.g +
185 ' can\'t be displayed in log scale for range [' +
186 axis.minyval + ' - ' + axis.maxyval + ']');
187 }
188 }
189 }
190};
191
7f028980
DV
192DygraphLayout._calcYNormal = function(axis, value) {
193 if (axis.logscale) {
194 return 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale);
195 } else {
196 return 1.0 - ((value - axis.minyval) * axis.yscale);
197 }
198};
199
74a5af31
DV
200DygraphLayout.prototype._evaluateLineCharts = function() {
201 // add all the rects
202 this.points = new Array();
c3e1495b
AR
203 // An array to keep track of how many points will be drawn for each set.
204 // This will allow for the canvas renderer to not have to check every point
fc77253b
DV
205 // for every data set since the points are added in order of the sets in
206 // datasets.
c3e1495b
AR
207 this.setPointsLengths = new Array();
208
74a5af31
DV
209 for (var setName in this.datasets) {
210 if (!this.datasets.hasOwnProperty(setName)) continue;
211
212 var dataset = this.datasets[setName];
213 var axis = this.dygraph_.axisPropertiesForSeries(setName);
214
c3e1495b 215 var setPointsLength = 0;
ecf9b464 216
74a5af31
DV
217 for (var j = 0; j < dataset.length; j++) {
218 var item = dataset[j];
4ab8db0c
AR
219 var xValue = parseFloat(dataset[j][0]);
220 var yValue = parseFloat(dataset[j][1]);
ecf9b464 221
4ab8db0c 222 // Range from 0-1 where 0 represents left and 1 represents right.
7f028980
DV
223 var xNormal = (xValue - this.minxval) * this.xscale;
224 // Range from 0-1 where 0 represents top and 1 represents bottom
225 var yNormal = DygraphLayout._calcYNormal(axis, yValue);
226
f9414b11
DV
227 var point = {
228 // TODO(danvk): here
229 x: xNormal,
230 y: yNormal,
231 xval: xValue,
232 yval: yValue,
233 name: setName
234 };
235 this.points.push(point);
236 setPointsLength += 1;
74a5af31 237 }
c3e1495b 238 this.setPointsLengths.push(setPointsLength);
74a5af31
DV
239 }
240};
241
242DygraphLayout.prototype._evaluateLineTicks = function() {
243 this.xticks = new Array();
244 for (var i = 0; i < this.xTicks_.length; i++) {
245 var tick = this.xTicks_[i];
246 var label = tick.label;
247 var pos = this.xscale * (tick.v - this.minxval);
248 if ((pos >= 0.0) && (pos <= 1.0)) {
249 this.xticks.push([pos, label]);
250 }
251 }
252
253 this.yticks = new Array();
254 for (var i = 0; i < this.yAxes_.length; i++ ) {
255 var axis = this.yAxes_[i];
256 for (var j = 0; j < axis.ticks.length; j++) {
257 var tick = axis.ticks[j];
258 var label = tick.label;
259 var pos = this.dygraph_.toPercentYCoord(tick.v, i);
260 if ((pos >= 0.0) && (pos <= 1.0)) {
261 this.yticks.push([i, pos, label]);
262 }
263 }
264 }
265};
266
267
268/**
269 * Behaves the same way as PlotKit.Layout, but also copies the errors
270 * @private
271 */
272DygraphLayout.prototype.evaluateWithError = function() {
273 this.evaluate();
274 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
275
276 // Copy over the error terms
277 var i = 0; // index in this.points
278 for (var setName in this.datasets) {
279 if (!this.datasets.hasOwnProperty(setName)) continue;
280 var j = 0;
281 var dataset = this.datasets[setName];
7f028980 282 var axis = this.dygraph_.axisPropertiesForSeries(setName);
74a5af31
DV
283 for (var j = 0; j < dataset.length; j++, i++) {
284 var item = dataset[j];
285 var xv = parseFloat(item[0]);
286 var yv = parseFloat(item[1]);
287
288 if (xv == this.points[i].xval &&
289 yv == this.points[i].yval) {
7f028980
DV
290 var errorMinus = parseFloat(item[2]);
291 var errorPlus = parseFloat(item[3]);
292
293 var yv_minus = yv - errorMinus;
294 var yv_plus = yv + errorPlus;
295 this.points[i].y_top = DygraphLayout._calcYNormal(axis, yv_minus);
296 this.points[i].y_bottom = DygraphLayout._calcYNormal(axis, yv_plus);
74a5af31
DV
297 }
298 }
299 }
300};
301
302DygraphLayout.prototype._evaluateAnnotations = function() {
303 // Add the annotations to the point to which they belong.
304 // Make a map from (setName, xval) to annotation for quick lookups.
305 var annotations = {};
306 for (var 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 = [];
d570a072
AR
312
313 // Exit the function early if there are no annotations.
314 if (!this.annotations || !this.annotations.length) {
315 return;
316 }
ccd9d7c2 317
d570a072 318 // TODO(antrob): loop through annotations not points.
74a5af31
DV
319 for (var i = 0; i < this.points.length; i++) {
320 var p = this.points[i];
321 var k = p.xval + "," + p.name;
322 if (k in annotations) {
323 p.annotation = annotations[k];
324 this.annotated_points.push(p);
325 }
326 }
327};
328
329/**
330 * Convenience function to remove all the data sets from a graph
331 */
332DygraphLayout.prototype.removeAllDatasets = function() {
333 delete this.datasets;
334 this.datasets = new Array();
335};
336
337/**
338 * Return a copy of the point at the indicated index, with its yval unstacked.
339 * @param int index of point in layout_.points
340 */
341DygraphLayout.prototype.unstackPointAtIndex = function(idx) {
342 var point = this.points[idx];
ccd9d7c2 343
74a5af31 344 // Clone the point since we modify it
ccd9d7c2 345 var unstackedPoint = {};
74a5af31
DV
346 for (var i in point) {
347 unstackedPoint[i] = point[i];
348 }
ccd9d7c2 349
74a5af31
DV
350 if (!this.attr_("stackedGraph")) {
351 return unstackedPoint;
352 }
ccd9d7c2
PF
353
354 // The unstacked yval is equal to the current yval minus the yval of the
74a5af31
DV
355 // next point at the same xval.
356 for (var i = idx+1; i < this.points.length; i++) {
357 if (this.points[i].xval == point.xval) {
ccd9d7c2 358 unstackedPoint.yval -= this.points[i].yval;
74a5af31
DV
359 break;
360 }
361 }
ccd9d7c2 362
74a5af31 363 return unstackedPoint;
ccd9d7c2 364}