Merged stacked graph support from iownbey's version and added assorted
[dygraphs.git] / dygraph-canvas.js
CommitLineData
6a1aa64f
DV
1// Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2// All Rights Reserved.
3
4/**
3df0ccf0
DV
5 * @fileoverview Based on PlotKit, but modified to meet the needs of dygraphs.
6 * In particular, support for:
7 * - grid overlays
8 * - error bars
9 * - dygraphs attribute system
6a1aa64f
DV
10 */
11
6a1aa64f 12/**
3df0ccf0 13 * Creates a new DygraphLayout object.
6a1aa64f 14 * @param {Object} options Options for PlotKit.Layout
285a6bda 15 * @return {Object} The DygraphLayout object
6a1aa64f 16 */
efe0829a
DV
17DygraphLayout = function(dygraph, options) {
18 this.dygraph_ = dygraph;
19 this.options = {}; // TODO(danvk): remove, use attr_ instead.
fc80a396 20 Dygraph.update(this.options, options ? options : {});
efe0829a 21 this.datasets = new Array();
6a1aa64f 22};
efe0829a
DV
23
24DygraphLayout.prototype.attr_ = function(name) {
25 return this.dygraph_.attr_(name);
26};
27
28DygraphLayout.prototype.addDataset = function(setname, set_xy) {
29 this.datasets[setname] = set_xy;
30};
31
32DygraphLayout.prototype.evaluate = function() {
33 this._evaluateLimits();
34 this._evaluateLineCharts();
35 this._evaluateLineTicks();
36};
37
38DygraphLayout.prototype._evaluateLimits = function() {
39 this.minxval = this.maxxval = null;
f6401bf6
DV
40 if (this.options.dateWindow) {
41 this.minxval = this.options.dateWindow[0];
42 this.maxxval = this.options.dateWindow[1];
43 } else {
44 for (var name in this.datasets) {
45 if (!this.datasets.hasOwnProperty(name)) continue;
46 var series = this.datasets[name];
47 var x1 = series[0][0];
48 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
85b99f0b 49
f6401bf6
DV
50 var x2 = series[series.length - 1][0];
51 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
52 }
efe0829a
DV
53 }
54 this.xrange = this.maxxval - this.minxval;
55 this.xscale = (this.xrange != 0 ? 1/this.xrange : 1.0);
56
57 this.minyval = this.options.yAxis[0];
58 this.maxyval = this.options.yAxis[1];
59 this.yrange = this.maxyval - this.minyval;
60 this.yscale = (this.yrange != 0 ? 1/this.yrange : 1.0);
61};
62
63DygraphLayout.prototype._evaluateLineCharts = function() {
64 // add all the rects
65 this.points = new Array();
66 for (var setName in this.datasets) {
85b99f0b
DV
67 if (!this.datasets.hasOwnProperty(setName)) continue;
68
69 var dataset = this.datasets[setName];
70 for (var j = 0; j < dataset.length; j++) {
71 var item = dataset[j];
72 var point = {
ff00d3e2 73 // TODO(danvk): here
85b99f0b
DV
74 x: ((parseFloat(item[0]) - this.minxval) * this.xscale),
75 y: 1.0 - ((parseFloat(item[1]) - this.minyval) * this.yscale),
76 xval: parseFloat(item[0]),
77 yval: parseFloat(item[1]),
78 name: setName
79 };
80
81 // limit the x, y values so they do not overdraw
82 if (point.y <= 0.0) {
83 point.y = 0.0;
84 }
85 if (point.y >= 1.0) {
86 point.y = 1.0;
87 }
88 if ((point.x >= 0.0) && (point.x <= 1.0)) {
89 this.points.push(point);
90 }
91 }
efe0829a
DV
92 }
93};
94
95DygraphLayout.prototype._evaluateLineTicks = function() {
96 this.xticks = new Array();
97 for (var i = 0; i < this.options.xTicks.length; i++) {
98 var tick = this.options.xTicks[i];
99 var label = tick.label;
100 var pos = this.xscale * (tick.v - this.minxval);
101 if ((pos >= 0.0) && (pos <= 1.0)) {
102 this.xticks.push([pos, label]);
103 }
104 }
105
106 this.yticks = new Array();
107 for (var i = 0; i < this.options.yTicks.length; i++) {
108 var tick = this.options.yTicks[i];
109 var label = tick.label;
110 var pos = 1.0 - (this.yscale * (tick.v - this.minyval));
111 if ((pos >= 0.0) && (pos <= 1.0)) {
112 this.yticks.push([pos, label]);
113 }
114 }
115};
116
6a1aa64f
DV
117
118/**
119 * Behaves the same way as PlotKit.Layout, but also copies the errors
120 * @private
121 */
285a6bda 122DygraphLayout.prototype.evaluateWithError = function() {
6a1aa64f
DV
123 this.evaluate();
124 if (!this.options.errorBars) return;
125
126 // Copy over the error terms
127 var i = 0; // index in this.points
128 for (var setName in this.datasets) {
85b99f0b
DV
129 if (!this.datasets.hasOwnProperty(setName)) continue;
130 var j = 0;
131 var dataset = this.datasets[setName];
132 for (var j = 0; j < dataset.length; j++, i++) {
133 var item = dataset[j];
134 var xv = parseFloat(item[0]);
135 var yv = parseFloat(item[1]);
136
137 if (xv == this.points[i].xval &&
138 yv == this.points[i].yval) {
139 this.points[i].errorMinus = parseFloat(item[2]);
140 this.points[i].errorPlus = parseFloat(item[3]);
141 }
142 }
6a1aa64f
DV
143 }
144};
145
146/**
147 * Convenience function to remove all the data sets from a graph
148 */
285a6bda 149DygraphLayout.prototype.removeAllDatasets = function() {
6a1aa64f
DV
150 delete this.datasets;
151 this.datasets = new Array();
152};
153
154/**
155 * Change the values of various layout options
156 * @param {Object} new_options an associative array of new properties
157 */
285a6bda 158DygraphLayout.prototype.updateOptions = function(new_options) {
fc80a396 159 Dygraph.update(this.options, new_options ? new_options : {});
6a1aa64f
DV
160};
161
162// Subclass PlotKit.CanvasRenderer to add:
163// 1. X/Y grid overlay
164// 2. Ability to draw error bars (if required)
165
166/**
167 * Sets some PlotKit.CanvasRenderer options
168 * @param {Object} element The canvas to attach to
285a6bda 169 * @param {Layout} layout The DygraphLayout object for this graph.
6a1aa64f
DV
170 * @param {Object} options Options to pass on to CanvasRenderer
171 */
9317362d
DV
172DygraphCanvasRenderer = function(dygraph, element, layout, options) {
173 // TODO(danvk): remove options, just use dygraph.attr_.
9317362d 174 this.dygraph_ = dygraph;
fbe31dc8
DV
175
176 // default options
177 this.options = {
f474c2a3
DV
178 "strokeWidth": 0.5,
179 "drawXAxis": true,
180 "drawYAxis": true,
181 "axisLineColor": "black",
182 "axisLineWidth": 0.5,
183 "axisTickSize": 3,
184 "axisLabelColor": "black",
185 "axisLabelFont": "Arial",
186 "axisLabelFontSize": 9,
187 "axisLabelWidth": 50,
188 "drawYGrid": true,
189 "drawXGrid": true,
43af96e7
NK
190 "gridLineColor": "rgb(128,128,128)",
191 "fillAlpha": 0.15,
fbe31dc8 192 };
fc80a396 193 Dygraph.update(this.options, options);
6a1aa64f 194
fbe31dc8 195 this.layout = layout;
b0c3b730 196 this.element = element;
fbe31dc8
DV
197 this.container = this.element.parentNode;
198
fbe31dc8
DV
199 this.height = this.element.height;
200 this.width = this.element.width;
201
202 // --- check whether everything is ok before we return
203 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
204 throw "Canvas is not supported.";
205
206 // internal state
207 this.xlabels = new Array();
208 this.ylabels = new Array();
209
210 this.area = {
211 x: this.options.yAxisLabelWidth + 2 * this.options.axisTickSize,
212 y: 0
213 };
214 this.area.w = this.width - this.area.x - this.options.rightGap;
215 this.area.h = this.height - this.options.axisLabelFontSize -
216 2 * this.options.axisTickSize;
217
b0c3b730
DV
218 this.container.style.position = "relative";
219 this.container.style.width = this.width + "px";
fbe31dc8
DV
220};
221
222DygraphCanvasRenderer.prototype.clear = function() {
223 if (this.isIE) {
224 // VML takes a while to start up, so we just poll every this.IEDelay
225 try {
226 if (this.clearDelay) {
227 this.clearDelay.cancel();
228 this.clearDelay = null;
229 }
230 var context = this.element.getContext("2d");
231 }
232 catch (e) {
76171648 233 // TODO(danvk): this is broken, since MochiKit.Async is gone.
fbe31dc8
DV
234 this.clearDelay = MochiKit.Async.wait(this.IEDelay);
235 this.clearDelay.addCallback(bind(this.clear, this));
236 return;
237 }
238 }
239
240 var context = this.element.getContext("2d");
241 context.clearRect(0, 0, this.width, this.height);
242
2160ed4a 243 for (var i = 0; i < this.xlabels.length; i++) {
b0c3b730
DV
244 var el = this.xlabels[i];
245 el.parentNode.removeChild(el);
2160ed4a
DV
246 }
247 for (var i = 0; i < this.ylabels.length; i++) {
b0c3b730
DV
248 var el = this.ylabels[i];
249 el.parentNode.removeChild(el);
2160ed4a 250 }
fbe31dc8
DV
251 this.xlabels = new Array();
252 this.ylabels = new Array();
253};
254
255
256DygraphCanvasRenderer.isSupported = function(canvasName) {
257 var canvas = null;
258 try {
21d3323f 259 if (typeof(canvasName) == 'undefined' || canvasName == null)
b0c3b730 260 canvas = document.createElement("canvas");
fbe31dc8 261 else
b0c3b730 262 canvas = canvasName;
fbe31dc8
DV
263 var context = canvas.getContext("2d");
264 }
265 catch (e) {
266 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
267 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
268 if ((!ie) || (ie[1] < 6) || (opera))
269 return false;
270 return true;
271 }
272 return true;
6a1aa64f 273};
6a1aa64f
DV
274
275/**
276 * Draw an X/Y grid on top of the existing plot
277 */
285a6bda 278DygraphCanvasRenderer.prototype.render = function() {
6a1aa64f
DV
279 // Draw the new X/Y grid
280 var ctx = this.element.getContext("2d");
281 if (this.options.drawYGrid) {
282 var ticks = this.layout.yticks;
283 ctx.save();
f2f24402 284 ctx.strokeStyle = this.options.gridLineColor;
6a1aa64f
DV
285 ctx.lineWidth = this.options.axisLineWidth;
286 for (var i = 0; i < ticks.length; i++) {
287 var x = this.area.x;
288 var y = this.area.y + ticks[i][0] * this.area.h;
289 ctx.beginPath();
290 ctx.moveTo(x, y);
291 ctx.lineTo(x + this.area.w, y);
292 ctx.closePath();
293 ctx.stroke();
294 }
295 }
296
297 if (this.options.drawXGrid) {
298 var ticks = this.layout.xticks;
299 ctx.save();
f2f24402 300 ctx.strokeStyle = this.options.gridLineColor;
6a1aa64f
DV
301 ctx.lineWidth = this.options.axisLineWidth;
302 for (var i=0; i<ticks.length; i++) {
303 var x = this.area.x + ticks[i][0] * this.area.w;
304 var y = this.area.y + this.area.h;
305 ctx.beginPath();
306 ctx.moveTo(x, y);
307 ctx.lineTo(x, this.area.y);
308 ctx.closePath();
309 ctx.stroke();
310 }
311 }
2ce09b19
DV
312
313 // Do the ordinary rendering, as before
2ce09b19 314 this._renderLineChart();
fbe31dc8
DV
315 this._renderAxis();
316};
317
318
319DygraphCanvasRenderer.prototype._renderAxis = function() {
320 if (!this.options.drawXAxis && !this.options.drawYAxis)
321 return;
322
323 var context = this.element.getContext("2d");
324
34fedff8
DV
325 var labelStyle = {
326 "position": "absolute",
327 "fontSize": this.options.axisLabelFontSize + "px",
328 "zIndex": 10,
f474c2a3 329 "color": this.options.axisLabelColor,
34fedff8
DV
330 "width": this.options.axisLabelWidth + "px",
331 "overflow": "hidden"
332 };
333 var makeDiv = function(txt) {
334 var div = document.createElement("div");
335 for (var name in labelStyle) {
85b99f0b
DV
336 if (labelStyle.hasOwnProperty(name)) {
337 div.style[name] = labelStyle[name];
338 }
fbe31dc8 339 }
34fedff8
DV
340 div.appendChild(document.createTextNode(txt));
341 return div;
fbe31dc8
DV
342 };
343
344 // axis lines
345 context.save();
f474c2a3 346 context.strokeStyle = this.options.axisLineColor;
fbe31dc8
DV
347 context.lineWidth = this.options.axisLineWidth;
348
fbe31dc8 349 if (this.options.drawYAxis) {
8b7a0cc3 350 if (this.layout.yticks && this.layout.yticks.length > 0) {
2160ed4a
DV
351 for (var i = 0; i < this.layout.yticks.length; i++) {
352 var tick = this.layout.yticks[i];
fbe31dc8
DV
353 if (typeof(tick) == "function") return;
354 var x = this.area.x;
355 var y = this.area.y + tick[0] * this.area.h;
356 context.beginPath();
357 context.moveTo(x, y);
358 context.lineTo(x - this.options.axisTickSize, y);
359 context.closePath();
360 context.stroke();
361
34fedff8 362 var label = makeDiv(tick[1]);
fbe31dc8
DV
363 var top = (y - this.options.axisLabelFontSize / 2);
364 if (top < 0) top = 0;
365
366 if (top + this.options.axisLabelFontSize + 3 > this.height) {
367 label.style.bottom = "0px";
368 } else {
369 label.style.top = top + "px";
370 }
371 label.style.left = "0px";
372 label.style.textAlign = "right";
373 label.style.width = this.options.yAxisLabelWidth + "px";
b0c3b730 374 this.container.appendChild(label);
fbe31dc8 375 this.ylabels.push(label);
2160ed4a 376 }
fbe31dc8
DV
377
378 // The lowest tick on the y-axis often overlaps with the leftmost
379 // tick on the x-axis. Shift the bottom tick up a little bit to
380 // compensate if necessary.
381 var bottomTick = this.ylabels[0];
382 var fontSize = this.options.axisLabelFontSize;
383 var bottom = parseInt(bottomTick.style.top) + fontSize;
384 if (bottom > this.height - fontSize) {
385 bottomTick.style.top = (parseInt(bottomTick.style.top) -
386 fontSize / 2) + "px";
387 }
388 }
389
390 context.beginPath();
391 context.moveTo(this.area.x, this.area.y);
392 context.lineTo(this.area.x, this.area.y + this.area.h);
393 context.closePath();
394 context.stroke();
395 }
396
397 if (this.options.drawXAxis) {
398 if (this.layout.xticks) {
2160ed4a
DV
399 for (var i = 0; i < this.layout.xticks.length; i++) {
400 var tick = this.layout.xticks[i];
fbe31dc8
DV
401 if (typeof(dataset) == "function") return;
402
403 var x = this.area.x + tick[0] * this.area.w;
404 var y = this.area.y + this.area.h;
405 context.beginPath();
406 context.moveTo(x, y);
407 context.lineTo(x, y + this.options.axisTickSize);
408 context.closePath();
409 context.stroke();
410
34fedff8 411 var label = makeDiv(tick[1]);
fbe31dc8
DV
412 label.style.textAlign = "center";
413 label.style.bottom = "0px";
414
415 var left = (x - this.options.axisLabelWidth/2);
416 if (left + this.options.axisLabelWidth > this.width) {
417 left = this.width - this.options.xAxisLabelWidth;
418 label.style.textAlign = "right";
419 }
420 if (left < 0) {
421 left = 0;
422 label.style.textAlign = "left";
423 }
424
425 label.style.left = left + "px";
426 label.style.width = this.options.xAxisLabelWidth + "px";
b0c3b730 427 this.container.appendChild(label);
fbe31dc8 428 this.xlabels.push(label);
2160ed4a 429 }
fbe31dc8
DV
430 }
431
432 context.beginPath();
433 context.moveTo(this.area.x, this.area.y + this.area.h);
434 context.lineTo(this.area.x + this.area.w, this.area.y + this.area.h);
435 context.closePath();
436 context.stroke();
437 }
438
439 context.restore();
6a1aa64f
DV
440};
441
fbe31dc8 442
6a1aa64f
DV
443/**
444 * Overrides the CanvasRenderer method to draw error bars
445 */
285a6bda 446DygraphCanvasRenderer.prototype._renderLineChart = function() {
6a1aa64f
DV
447 var context = this.element.getContext("2d");
448 var colorCount = this.options.colorScheme.length;
449 var colorScheme = this.options.colorScheme;
43af96e7 450 var fillAlpha = this.options.fillAlpha;
6a1aa64f 451 var errorBars = this.layout.options.errorBars;
5954ef32 452 var fillGraph = this.layout.options.fillGraph;
21d3323f
DV
453
454 var setNames = [];
ca43052c 455 for (var name in this.layout.datasets) {
85b99f0b
DV
456 if (this.layout.datasets.hasOwnProperty(name)) {
457 setNames.push(name);
458 }
ca43052c 459 }
21d3323f 460 var setCount = setNames.length;
6a1aa64f 461
ff00d3e2
DV
462 // Update Points
463 // TODO(danvk): here
2160ed4a
DV
464 for (var i = 0; i < this.layout.points.length; i++) {
465 var point = this.layout.points[i];
6a1aa64f
DV
466 point.canvasx = this.area.w * point.x + this.area.x;
467 point.canvasy = this.area.h * point.y + this.area.y;
468 }
6a1aa64f
DV
469
470 // create paths
9317362d 471 var isOK = function(x) { return x && !isNaN(x); };
6a1aa64f 472
80aaae18
DV
473 var ctx = context;
474 if (errorBars) {
6a834bbb
DV
475 if (fillGraph) {
476 this.dygraph_.warn("Can't use fillGraph option with error bars");
477 }
478
6a1aa64f
DV
479 for (var i = 0; i < setCount; i++) {
480 var setName = setNames[i];
481 var color = colorScheme[i % colorCount];
6a1aa64f
DV
482
483 // setup graphics context
80aaae18
DV
484 ctx.save();
485 ctx.strokeStyle = color;
486 ctx.lineWidth = this.options.strokeWidth;
6a1aa64f
DV
487 var prevX = -1;
488 var prevYs = [-1, -1];
489 var count = 0;
490 var yscale = this.layout.yscale;
f474c2a3
DV
491 // should be same color as the lines but only 15% opaque.
492 var rgb = new RGBColor(color);
43af96e7
NK
493 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
494 fillAlpha + ')';
f474c2a3 495 ctx.fillStyle = err_color;
05c9d0c4
DV
496 ctx.beginPath();
497 for (var j = 0; j < this.layout.points.length; j++) {
498 var point = this.layout.points[j];
6a1aa64f
DV
499 count++;
500 if (point.name == setName) {
5954ef32 501 if (!isOK(point.y)) {
5011e7a1 502 prevX = -1;
ae85914a 503 continue;
5011e7a1 504 }
ff00d3e2 505 // TODO(danvk): here
6a1aa64f
DV
506 var newYs = [ point.y - point.errorPlus * yscale,
507 point.y + point.errorMinus * yscale ];
508 newYs[0] = this.area.h * newYs[0] + this.area.y;
509 newYs[1] = this.area.h * newYs[1] + this.area.y;
5954ef32
DV
510 if (prevX >= 0) {
511 ctx.moveTo(prevX, prevYs[0]);
512 ctx.lineTo(point.canvasx, newYs[0]);
513 ctx.lineTo(point.canvasx, newYs[1]);
514 ctx.lineTo(prevX, prevYs[1]);
515 ctx.closePath();
516 }
517 prevYs[0] = newYs[0];
518 prevYs[1] = newYs[1];
519 prevX = point.canvasx;
520 }
521 }
522 ctx.fill();
523 }
524 } else if (fillGraph) {
ff00d3e2 525 // TODO(danvk): merge this code with the logic above; they're very similar.
5954ef32
DV
526 for (var i = 0; i < setCount; i++) {
527 var setName = setNames[i];
528 var setNameLast;
529 if (i>0) setNameLast = setNames[i-1];
530 var color = colorScheme[i % colorCount];
531
532 // setup graphics context
533 ctx.save();
534 ctx.strokeStyle = color;
535 ctx.lineWidth = this.options.strokeWidth;
536 var prevX = -1;
537 var prevYs = [-1, -1];
538 var count = 0;
539 var yscale = this.layout.yscale;
540 // should be same color as the lines but only 15% opaque.
541 var rgb = new RGBColor(color);
43af96e7
NK
542 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
543 fillAlpha + ')';
5954ef32
DV
544 ctx.fillStyle = err_color;
545 ctx.beginPath();
546 for (var j = 0; j < this.layout.points.length; j++) {
547 var point = this.layout.points[j];
548 count++;
549 if (point.name == setName) {
550 if (!isOK(point.y)) {
551 prevX = -1;
552 continue;
553 }
554 var pX = 1.0 + this.layout.minyval * this.layout.yscale;
555 if (pX < 0.0) pX = 0.0;
556 else if (pX > 1.0) pX = 1.0;
557 var newYs = [ point.y, pX ];
558 newYs[0] = this.area.h * newYs[0] + this.area.y;
559 newYs[1] = this.area.h * newYs[1] + this.area.y;
6a1aa64f 560 if (prevX >= 0) {
05c9d0c4
DV
561 ctx.moveTo(prevX, prevYs[0]);
562 ctx.lineTo(point.canvasx, newYs[0]);
563 ctx.lineTo(point.canvasx, newYs[1]);
564 ctx.lineTo(prevX, prevYs[1]);
565 ctx.closePath();
6a1aa64f
DV
566 }
567 prevYs[0] = newYs[0];
568 prevYs[1] = newYs[1];
569 prevX = point.canvasx;
570 }
05c9d0c4 571 }
6a1aa64f
DV
572 ctx.fill();
573 }
80aaae18
DV
574 }
575
576 for (var i = 0; i < setCount; i++) {
577 var setName = setNames[i];
578 var color = colorScheme[i%colorCount];
579
580 // setup graphics context
581 context.save();
582 var point = this.layout.points[0];
583 var pointSize = this.dygraph_.attr_("pointSize");
584 var prevX = null, prevY = null;
585 var drawPoints = this.dygraph_.attr_("drawPoints");
586 var points = this.layout.points;
587 for (var j = 0; j < points.length; j++) {
588 var point = points[j];
589 if (point.name == setName) {
590 if (!isOK(point.canvasy)) {
591 // this will make us move to the next point, not draw a line to it.
592 prevX = prevY = null;
593 } else {
594 // A point is "isolated" if it is non-null but both the previous
595 // and next points are null.
596 var isIsolated = (!prevX && (j == points.length - 1 ||
597 !isOK(points[j+1].canvasy)));
598
599 if (!prevX) {
600 prevX = point.canvasx;
601 prevY = point.canvasy;
602 } else {
603 ctx.beginPath();
604 ctx.strokeStyle = color;
605 ctx.lineWidth = this.options.strokeWidth;
606 ctx.moveTo(prevX, prevY);
607 prevX = point.canvasx;
608 prevY = point.canvasy;
609 ctx.lineTo(prevX, prevY);
610 ctx.stroke();
611 }
612
613 if (drawPoints || isIsolated) {
614 ctx.beginPath();
615 ctx.fillStyle = color;
7bf6a9fe
DV
616 ctx.arc(point.canvasx, point.canvasy, pointSize,
617 0, 2 * Math.PI, false);
80aaae18
DV
618 ctx.fill();
619 }
620 }
621 }
622 }
623 }
6a1aa64f 624
6a1aa64f
DV
625 context.restore();
626};