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