1 // Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2 // All Rights Reserved.
5 * @fileoverview Based on PlotKit, but modified to meet the needs of dygraphs.
6 * In particular, support for:
9 * - dygraphs attribute system
13 * Creates a new DygraphLayout object.
14 * @param {Object} options Options for PlotKit.Layout
15 * @return {Object} The DygraphLayout object
17 DygraphLayout
= function(dygraph
, options
) {
18 this.dygraph_
= dygraph
;
19 this.options
= {}; // TODO(danvk): remove, use attr_ instead.
20 Dygraph
.update(this.options
, options
? options
: {});
21 this.datasets
= new Array();
22 this.annotations
= new Array()
25 DygraphLayout
.prototype.attr_
= function(name
) {
26 return this.dygraph_
.attr_(name
);
29 DygraphLayout
.prototype.addDataset
= function(setname
, set_xy
) {
30 this.datasets
[setname
] = set_xy
;
33 // TODO(danvk): CONTRACT remove
34 DygraphLayout
.prototype.setAnnotations
= function(ann
) {
35 // The Dygraph object's annotations aren't parsed. We parse them here and
37 var parse
= this.attr_('xValueParser');
38 for (var i
= 0; i
< ann
.length
; i
++) {
41 this.dygraph_
.error("Annotations must have an 'x' property");
44 Dygraph
.update(a
, ann
[i
]);
46 this.annotations
.push(a
);
50 DygraphLayout
.prototype.evaluate
= function() {
51 this._evaluateLimits();
52 this._evaluateLineCharts();
53 this._evaluateLineTicks();
54 this._evaluateAnnotations();
57 DygraphLayout
.prototype._evaluateLimits
= function() {
58 this.minxval
= this.maxxval
= null;
59 if (this.options
.dateWindow
) {
60 this.minxval
= this.options
.dateWindow
[0];
61 this.maxxval
= this.options
.dateWindow
[1];
63 for (var name
in this.datasets
) {
64 if (!this.datasets
.hasOwnProperty(name
)) continue;
65 var series
= this.datasets
[name
];
66 var x1
= series
[0][0];
67 if (!this.minxval
|| x1
< this.minxval
) this.minxval
= x1
;
69 var x2
= series
[series
.length
- 1][0];
70 if (!this.maxxval
|| x2
> this.maxxval
) this.maxxval
= x2
;
73 this.xrange
= this.maxxval
- this.minxval
;
74 this.xscale
= (this.xrange
!= 0 ? 1/this.xrange
: 1.0);
76 this.minyval
= this.options
.yAxis
[0];
77 this.maxyval
= this.options
.yAxis
[1];
78 this.yrange
= this.maxyval
- this.minyval
;
79 this.yscale
= (this.yrange
!= 0 ? 1/this.yrange
: 1.0);
82 DygraphLayout
.prototype._evaluateLineCharts
= function() {
84 this.points
= new Array();
85 for (var setName
in this.datasets
) {
86 if (!this.datasets
.hasOwnProperty(setName
)) continue;
88 var dataset
= this.datasets
[setName
];
89 for (var j
= 0; j
< dataset
.length
; j
++) {
90 var item
= dataset
[j
];
93 x
: ((parseFloat(item
[0]) - this.minxval
) * this.xscale
),
94 y
: 1.0 - ((parseFloat(item
[1]) - this.minyval
) * this.yscale
),
95 xval
: parseFloat(item
[0]),
96 yval
: parseFloat(item
[1]),
100 // limit the x, y values so they do not overdraw
101 if (point
.y
<= 0.0) {
104 if (point
.y
>= 1.0) {
107 this.points
.push(point
);
112 DygraphLayout
.prototype._evaluateLineTicks
= function() {
113 this.xticks
= new Array();
114 for (var i
= 0; i
< this.options
.xTicks
.length
; i
++) {
115 var tick
= this.options
.xTicks
[i
];
116 var label
= tick
.label
;
117 var pos
= this.xscale
* (tick
.v
- this.minxval
);
118 if ((pos
>= 0.0) && (pos
<= 1.0)) {
119 this.xticks
.push([pos
, label
]);
123 this.yticks
= new Array();
124 for (var i
= 0; i
< this.options
.yTicks
.length
; i
++) {
125 var tick
= this.options
.yTicks
[i
];
126 var label
= tick
.label
;
127 var pos
= 1.0 - (this.yscale
* (tick
.v
- this.minyval
));
128 if ((pos
>= 0.0) && (pos
<= 1.0)) {
129 this.yticks
.push([pos
, label
]);
136 * Behaves the same way as PlotKit.Layout, but also copies the errors
139 DygraphLayout
.prototype.evaluateWithError
= function() {
141 if (!this.options
.errorBars
) return;
143 // Copy over the error terms
144 var i
= 0; // index in this.points
145 for (var setName
in this.datasets
) {
146 if (!this.datasets
.hasOwnProperty(setName
)) continue;
148 var dataset
= this.datasets
[setName
];
149 for (var j
= 0; j
< dataset
.length
; j
++, i
++) {
150 var item
= dataset
[j
];
151 var xv
= parseFloat(item
[0]);
152 var yv
= parseFloat(item
[1]);
154 if (xv
== this.points
[i
].xval
&&
155 yv
== this.points
[i
].yval
) {
156 this.points
[i
].errorMinus
= parseFloat(item
[2]);
157 this.points
[i
].errorPlus
= parseFloat(item
[3]);
163 DygraphLayout
.prototype._evaluateAnnotations
= function() {
164 // Add the annotations to the point to which they belong.
165 // Make a map from (setName, xval) to annotation for quick lookups.
166 var annotations
= {};
167 for (var i
= 0; i
< this.annotations
.length
; i
++) {
168 var a
= this.annotations
[i
];
169 annotations
[a
.xval
+ "," + a
.series
] = a
;
172 this.annotated_points
= [];
173 for (var i
= 0; i
< this.points
.length
; i
++) {
174 var p
= this.points
[i
];
175 var k
= p
.xval
+ "," + p
.name
;
176 if (k
in annotations
) {
177 p
.annotation
= annotations
[k
];
178 this.annotated_points
.push(p
);
184 * Convenience function to remove all the data sets from a graph
186 DygraphLayout
.prototype.removeAllDatasets
= function() {
187 delete this.datasets
;
188 this.datasets
= new Array();
192 * Change the values of various layout options
193 * @param {Object} new_options an associative array of new properties
195 DygraphLayout
.prototype.updateOptions
= function(new_options
) {
196 Dygraph
.update(this.options
, new_options
? new_options
: {});
199 // Subclass PlotKit.CanvasRenderer to add:
200 // 1. X/Y grid overlay
201 // 2. Ability to draw error bars (if required)
204 * Sets some PlotKit.CanvasRenderer options
205 * @param {Object} element The canvas to attach to
206 * @param {Layout} layout The DygraphLayout object for this graph.
207 * @param {Object} options Options to pass on to CanvasRenderer
209 DygraphCanvasRenderer
= function(dygraph
, element
, layout
, options
) {
210 // TODO(danvk): remove options, just use dygraph.attr_.
211 this.dygraph_
= dygraph
;
218 "axisLineColor": "black",
219 "axisLineWidth": 0.5,
221 "axisLabelColor": "black",
222 "axisLabelFont": "Arial",
223 "axisLabelFontSize": 9,
224 "axisLabelWidth": 50,
227 "gridLineColor": "rgb(128,128,128)",
229 "underlayCallback": null
231 Dygraph
.update(this.options
, options
);
233 this.layout
= layout
;
234 this.element
= element
;
235 this.container
= this.element
.parentNode
;
237 this.height
= this.element
.height
;
238 this.width
= this.element
.width
;
240 // --- check whether everything is ok before we return
241 if (!this.isIE
&& !(DygraphCanvasRenderer
.isSupported(this.element
)))
242 throw "Canvas is not supported.";
245 this.xlabels
= new Array();
246 this.ylabels
= new Array();
247 this.annotations
= new Array();
250 x
: this.options
.yAxisLabelWidth
+ 2 * this.options
.axisTickSize
,
253 this.area
.w
= this.width
- this.area
.x
- this.options
.rightGap
;
254 this.area
.h
= this.height
- this.options
.axisLabelFontSize
-
255 2 * this.options
.axisTickSize
;
257 this.container
.style
.position
= "relative";
258 this.container
.style
.width
= this.width
+ "px";
261 DygraphCanvasRenderer
.prototype.clear
= function() {
263 // VML takes a while to start up, so we just poll every this.IEDelay
265 if (this.clearDelay
) {
266 this.clearDelay
.cancel();
267 this.clearDelay
= null;
269 var context
= this.element
.getContext("2d");
272 // TODO(danvk): this is broken, since MochiKit.Async is gone.
273 this.clearDelay
= MochiKit
.Async
.wait(this.IEDelay
);
274 this.clearDelay
.addCallback(bind(this.clear
, this));
279 var context
= this.element
.getContext("2d");
280 context
.clearRect(0, 0, this.width
, this.height
);
282 for (var i
= 0; i
< this.xlabels
.length
; i
++) {
283 var el
= this.xlabels
[i
];
284 el
.parentNode
.removeChild(el
);
286 for (var i
= 0; i
< this.ylabels
.length
; i
++) {
287 var el
= this.ylabels
[i
];
288 el
.parentNode
.removeChild(el
);
290 for (var i
= 0; i
< this.annotations
.length
; i
++) {
291 var el
= this.annotations
[i
];
292 el
.parentNode
.removeChild(el
);
294 this.xlabels
= new Array();
295 this.ylabels
= new Array();
296 this.annotations
= new Array();
300 DygraphCanvasRenderer
.isSupported
= function(canvasName
) {
303 if (typeof(canvasName
) == 'undefined' || canvasName
== null)
304 canvas
= document
.createElement("canvas");
307 var context
= canvas
.getContext("2d");
310 var ie
= navigator
.appVersion
.match(/MSIE (\d\.\d)/);
311 var opera
= (navigator
.userAgent
.toLowerCase().indexOf("opera") != -1);
312 if ((!ie
) || (ie
[1] < 6) || (opera
))
320 * Draw an X/Y grid on top of the existing plot
322 DygraphCanvasRenderer
.prototype.render
= function() {
323 // Draw the new X/Y grid
324 var ctx
= this.element
.getContext("2d");
326 if (this.options
.underlayCallback
) {
327 this.options
.underlayCallback(ctx
, this.area
, this.layout
, this.dygraph_
);
330 if (this.options
.drawYGrid
) {
331 var ticks
= this.layout
.yticks
;
333 ctx
.strokeStyle
= this.options
.gridLineColor
;
334 ctx
.lineWidth
= this.options
.axisLineWidth
;
335 for (var i
= 0; i
< ticks
.length
; i
++) {
337 var y
= this.area
.y
+ ticks
[i
][0] * this.area
.h
;
340 ctx
.lineTo(x
+ this.area
.w
, y
);
346 if (this.options
.drawXGrid
) {
347 var ticks
= this.layout
.xticks
;
349 ctx
.strokeStyle
= this.options
.gridLineColor
;
350 ctx
.lineWidth
= this.options
.axisLineWidth
;
351 for (var i
=0; i
<ticks
.length
; i
++) {
352 var x
= this.area
.x
+ ticks
[i
][0] * this.area
.w
;
353 var y
= this.area
.y
+ this.area
.h
;
356 ctx
.lineTo(x
, this.area
.y
);
362 // Do the ordinary rendering, as before
363 this._renderLineChart();
365 this._renderAnnotations();
369 DygraphCanvasRenderer
.prototype._renderAxis
= function() {
370 if (!this.options
.drawXAxis
&& !this.options
.drawYAxis
)
373 var context
= this.element
.getContext("2d");
376 "position": "absolute",
377 "fontSize": this.options
.axisLabelFontSize
+ "px",
379 "color": this.options
.axisLabelColor
,
380 "width": this.options
.axisLabelWidth
+ "px",
383 var makeDiv
= function(txt
) {
384 var div
= document
.createElement("div");
385 for (var name
in labelStyle
) {
386 if (labelStyle
.hasOwnProperty(name
)) {
387 div
.style
[name
] = labelStyle
[name
];
390 div
.appendChild(document
.createTextNode(txt
));
396 context
.strokeStyle
= this.options
.axisLineColor
;
397 context
.lineWidth
= this.options
.axisLineWidth
;
399 if (this.options
.drawYAxis
) {
400 if (this.layout
.yticks
&& this.layout
.yticks
.length
> 0) {
401 for (var i
= 0; i
< this.layout
.yticks
.length
; i
++) {
402 var tick
= this.layout
.yticks
[i
];
403 if (typeof(tick
) == "function") return;
405 var y
= this.area
.y
+ tick
[0] * this.area
.h
;
407 context
.moveTo(x
, y
);
408 context
.lineTo(x
- this.options
.axisTickSize
, y
);
412 var label
= makeDiv(tick
[1]);
413 var top
= (y
- this.options
.axisLabelFontSize
/ 2);
414 if (top
< 0) top
= 0;
416 if (top
+ this.options
.axisLabelFontSize
+ 3 > this.height
) {
417 label
.style
.bottom
= "0px";
419 label
.style
.top
= top
+ "px";
421 label
.style
.left
= "0px";
422 label
.style
.textAlign
= "right";
423 label
.style
.width
= this.options
.yAxisLabelWidth
+ "px";
424 this.container
.appendChild(label
);
425 this.ylabels
.push(label
);
428 // The lowest tick on the y-axis often overlaps with the leftmost
429 // tick on the x-axis. Shift the bottom tick up a little bit to
430 // compensate if necessary.
431 var bottomTick
= this.ylabels
[0];
432 var fontSize
= this.options
.axisLabelFontSize
;
433 var bottom
= parseInt(bottomTick
.style
.top
) + fontSize
;
434 if (bottom
> this.height
- fontSize
) {
435 bottomTick
.style
.top
= (parseInt(bottomTick
.style
.top
) -
436 fontSize
/ 2) + "px";
441 context
.moveTo(this.area
.x
, this.area
.y
);
442 context
.lineTo(this.area
.x
, this.area
.y
+ this.area
.h
);
447 if (this.options
.drawXAxis
) {
448 if (this.layout
.xticks
) {
449 for (var i
= 0; i
< this.layout
.xticks
.length
; i
++) {
450 var tick
= this.layout
.xticks
[i
];
451 if (typeof(dataset
) == "function") return;
453 var x
= this.area
.x
+ tick
[0] * this.area
.w
;
454 var y
= this.area
.y
+ this.area
.h
;
456 context
.moveTo(x
, y
);
457 context
.lineTo(x
, y
+ this.options
.axisTickSize
);
461 var label
= makeDiv(tick
[1]);
462 label
.style
.textAlign
= "center";
463 label
.style
.bottom
= "0px";
465 var left
= (x
- this.options
.axisLabelWidth
/2);
466 if (left
+ this.options
.axisLabelWidth
> this.width
) {
467 left
= this.width
- this.options
.xAxisLabelWidth
;
468 label
.style
.textAlign
= "right";
472 label
.style
.textAlign
= "left";
475 label
.style
.left
= left
+ "px";
476 label
.style
.width
= this.options
.xAxisLabelWidth
+ "px";
477 this.container
.appendChild(label
);
478 this.xlabels
.push(label
);
483 context
.moveTo(this.area
.x
, this.area
.y
+ this.area
.h
);
484 context
.lineTo(this.area
.x
+ this.area
.w
, this.area
.y
+ this.area
.h
);
493 DygraphCanvasRenderer
.prototype._renderAnnotations
= function() {
494 var annotationStyle
= {
495 "position": "absolute",
496 "fontSize": this.options
.axisLabelFontSize
+ "px",
499 "overflow": "hidden",
502 var bindEvt
= function(eventName
, classEventName
, p
, self
) {
504 var a
= p
.annotation
;
505 if (a
.hasOwnProperty(eventName
)) {
506 a
[eventName
](a
, p
, self
.dygraph_
, e
);
507 } else if (self
.dygraph_
.attr_(classEventName
)) {
508 self
.dygraph_
.attr_(classEventName
)(a
, p
, self
.dygraph_
,e
);
513 // Get a list of point with annotations.
514 var points
= this.layout
.annotated_points
;
515 for (var i
= 0; i
< points
.length
; i
++) {
517 var div
= document
.createElement("div");
518 for (var name
in annotationStyle
) {
519 if (annotationStyle
.hasOwnProperty(name
)) {
520 div
.style
[name
] = annotationStyle
[name
];
523 div
.className
= "dygraphDefaultAnnotation";
524 if (p
.annotation
.hasOwnProperty('cssClass')) {
525 div
.className
+= " " + p
.annotation
.cssClass
;
527 div
.appendChild(document
.createTextNode(p
.annotation
.shortText
));
528 div
.style
.left
= (p
.canvasx
- 10) + "px";
529 div
.style
.top
= p
.canvasy
+ "px";
530 div
.title
= p
.annotation
.text
;
531 div
.style
.color
= this.colors
[p
.name
];
532 div
.style
.borderColor
= this.colors
[p
.name
];
534 Dygraph
.addEvent(div
, 'click', bindEvt('clickHandler', 'annotationClickHandler', p
, this));
535 Dygraph
.addEvent(div
, 'mouseover', bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p
, this));
536 Dygraph
.addEvent(div
, 'mouseout', bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p
, this));
537 Dygraph
.addEvent(div
, 'dblclick', bindEvt('dblClickHandler', 'annotationDblClickHandler', p
, this));
539 this.container
.appendChild(div
);
540 this.annotations
.push(div
);
546 * Overrides the CanvasRenderer method to draw error bars
548 DygraphCanvasRenderer
.prototype._renderLineChart
= function() {
549 var context
= this.element
.getContext("2d");
550 var colorCount
= this.options
.colorScheme
.length
;
551 var colorScheme
= this.options
.colorScheme
;
552 var fillAlpha
= this.options
.fillAlpha
;
553 var errorBars
= this.layout
.options
.errorBars
;
554 var fillGraph
= this.layout
.options
.fillGraph
;
555 var stackedGraph
= this.layout
.options
.stackedGraph
;
556 var stepPlot
= this.layout
.options
.stepPlot
;
559 for (var name
in this.layout
.datasets
) {
560 if (this.layout
.datasets
.hasOwnProperty(name
)) {
564 var setCount
= setNames
.length
;
567 for (var i
= 0; i
< setCount
; i
++) {
568 this.colors
[setNames
[i
]] = colorScheme
[i
% colorCount
];
573 for (var i
= 0; i
< this.layout
.points
.length
; i
++) {
574 var point
= this.layout
.points
[i
];
575 point
.canvasx
= this.area
.w
* point
.x
+ this.area
.x
;
576 point
.canvasy
= this.area
.h
* point
.y
+ this.area
.y
;
580 var isOK
= function(x
) { return x
&& !isNaN(x
); };
585 this.dygraph_
.warn("Can't use fillGraph option with error bars");
588 for (var i
= 0; i
< setCount
; i
++) {
589 var setName
= setNames
[i
];
590 var color
= this.colors
[setName
];
592 // setup graphics context
596 var prevYs
= [-1, -1];
597 var yscale
= this.layout
.yscale
;
598 // should be same color as the lines but only 15% opaque.
599 var rgb
= new RGBColor(color
);
600 var err_color
= 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' +
602 ctx
.fillStyle
= err_color
;
604 for (var j
= 0; j
< this.layout
.points
.length
; j
++) {
605 var point
= this.layout
.points
[j
];
606 if (point
.name
== setName
) {
607 if (!isOK(point
.y
)) {
614 var newYs
= [ prevY
- point
.errorPlus
* yscale
,
615 prevY
+ point
.errorMinus
* yscale
];
618 var newYs
= [ point
.y
- point
.errorPlus
* yscale
,
619 point
.y
+ point
.errorMinus
* yscale
];
621 newYs
[0] = this.area
.h
* newYs
[0] + this.area
.y
;
622 newYs
[1] = this.area
.h
* newYs
[1] + this.area
.y
;
625 ctx
.moveTo(prevX
, newYs
[0]);
627 ctx
.moveTo(prevX
, prevYs
[0]);
629 ctx
.lineTo(point
.canvasx
, newYs
[0]);
630 ctx
.lineTo(point
.canvasx
, newYs
[1]);
632 ctx
.lineTo(prevX
, newYs
[1]);
634 ctx
.lineTo(prevX
, prevYs
[1]);
639 prevX
= point
.canvasx
;
644 } else if (fillGraph
) {
645 var axisY
= 1.0 + this.layout
.minyval
* this.layout
.yscale
;
646 if (axisY
< 0.0) axisY
= 0.0;
647 else if (axisY
> 1.0) axisY
= 1.0;
648 axisY
= this.area
.h
* axisY
+ this.area
.y
;
650 var baseline
= [] // for stacked graphs: baseline for filling
652 // process sets in reverse order (needed for stacked graphs)
653 for (var i
= setCount
- 1; i
>= 0; i
--) {
654 var setName
= setNames
[i
];
655 var color
= this.colors
[setName
];
657 // setup graphics context
660 var prevYs
= [-1, -1];
661 var yscale
= this.layout
.yscale
;
662 // should be same color as the lines but only 15% opaque.
663 var rgb
= new RGBColor(color
);
664 var err_color
= 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' +
666 ctx
.fillStyle
= err_color
;
668 for (var j
= 0; j
< this.layout
.points
.length
; j
++) {
669 var point
= this.layout
.points
[j
];
670 if (point
.name
== setName
) {
671 if (!isOK(point
.y
)) {
677 lastY
= baseline
[point
.canvasx
];
678 if (lastY
=== undefined
) lastY
= axisY
;
679 baseline
[point
.canvasx
] = point
.canvasy
;
680 newYs
= [ point
.canvasy
, lastY
];
682 newYs
= [ point
.canvasy
, axisY
];
685 ctx
.moveTo(prevX
, prevYs
[0]);
687 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
689 ctx
.lineTo(point
.canvasx
, newYs
[0]);
691 ctx
.lineTo(point
.canvasx
, newYs
[1]);
692 ctx
.lineTo(prevX
, prevYs
[1]);
696 prevX
= point
.canvasx
;
703 for (var i
= 0; i
< setCount
; i
++) {
704 var setName
= setNames
[i
];
705 var color
= this.colors
[setName
];
707 // setup graphics context
709 var point
= this.layout
.points
[0];
710 var pointSize
= this.dygraph_
.attr_("pointSize");
711 var prevX
= null, prevY
= null;
712 var drawPoints
= this.dygraph_
.attr_("drawPoints");
713 var points
= this.layout
.points
;
714 for (var j
= 0; j
< points
.length
; j
++) {
715 var point
= points
[j
];
716 if (point
.name
== setName
) {
717 if (!isOK(point
.canvasy
)) {
718 // this will make us move to the next point, not draw a line to it.
719 prevX
= prevY
= null;
721 // A point is "isolated" if it is non-null but both the previous
722 // and next points are null.
723 var isIsolated
= (!prevX
&& (j
== points
.length
- 1 ||
724 !isOK(points
[j
+1].canvasy
)));
727 prevX
= point
.canvasx
;
728 prevY
= point
.canvasy
;
731 ctx
.strokeStyle
= color
;
732 ctx
.lineWidth
= this.options
.strokeWidth
;
733 ctx
.moveTo(prevX
, prevY
);
735 ctx
.lineTo(point
.canvasx
, prevY
);
737 prevX
= point
.canvasx
;
738 prevY
= point
.canvasy
;
739 ctx
.lineTo(prevX
, prevY
);
743 if (drawPoints
|| isIsolated
) {
745 ctx
.fillStyle
= color
;
746 ctx
.arc(point
.canvasx
, point
.canvasy
, pointSize
,
747 0, 2 * Math
.PI
, false);