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
11 * High level overview of classes:
14 * This contains all the data to be charted.
15 * It uses data coordinates, but also records the chart range (in data
16 * coordinates) and hence is able to calculate percentage positions ('In
17 * this view, Point A lies 25% down the x-axis.')
18 * Two things that it does not do are:
19 * 1. Record pixel coordinates for anything.
20 * 2. (oddly) determine anything about the layout of chart elements.
21 * The naming is a vestige of Dygraph's original PlotKit roots.
23 * - DygraphCanvasRenderer
24 * This class determines the charting area (in pixel coordinates), maps the
25 * percentage coordinates in the DygraphLayout to pixels and draws them.
26 * It's also responsible for creating chart DOM elements, i.e. annotations,
27 * tick mark labels, the title and the x/y-axis labels.
31 * Creates a new DygraphLayout object.
32 * @return {Object} The DygraphLayout object
34 DygraphLayout
= function(dygraph
) {
35 this.dygraph_
= dygraph
;
36 this.datasets
= new Array();
37 this.annotations
= new Array();
40 // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
41 // yticks are outputs. Clean this up.
46 DygraphLayout
.prototype.attr_
= function(name
) {
47 return this.dygraph_
.attr_(name
);
50 DygraphLayout
.prototype.addDataset
= function(setname
, set_xy
) {
51 this.datasets
[setname
] = set_xy
;
54 DygraphLayout
.prototype.setAnnotations
= function(ann
) {
55 // The Dygraph object's annotations aren't parsed. We parse them here and
56 // save a copy. If there is no parser, then the user must be using raw format.
57 this.annotations
= [];
58 var parse
= this.attr_('xValueParser') || function(x
) { return x
; };
59 for (var i
= 0; i
< ann
.length
; i
++) {
61 if (!ann
[i
].xval
&& !ann
[i
].x
) {
62 this.dygraph_
.error("Annotations must have an 'x' property");
66 !(ann
[i
].hasOwnProperty('width') &&
67 ann
[i
].hasOwnProperty('height'))) {
68 this.dygraph_
.error("Must set width and height when setting " +
69 "annotation.icon property");
72 Dygraph
.update(a
, ann
[i
]);
73 if (!a
.xval
) a
.xval
= parse(a
.x
);
74 this.annotations
.push(a
);
78 DygraphLayout
.prototype.setXTicks
= function(xTicks
) {
79 this.xTicks_
= xTicks
;
82 // TODO(danvk): add this to the Dygraph object's API or move it into Layout.
83 DygraphLayout
.prototype.setYAxes
= function (yAxes
) {
87 DygraphLayout
.prototype.setDateWindow
= function(dateWindow
) {
88 this.dateWindow_
= dateWindow
;
91 DygraphLayout
.prototype.evaluate
= function() {
92 this._evaluateLimits();
93 this._evaluateLineCharts();
94 this._evaluateLineTicks();
95 this._evaluateAnnotations();
98 DygraphLayout
.prototype._evaluateLimits
= function() {
99 this.minxval
= this.maxxval
= null;
100 if (this.dateWindow_
) {
101 this.minxval
= this.dateWindow_
[0];
102 this.maxxval
= this.dateWindow_
[1];
104 for (var name
in this.datasets
) {
105 if (!this.datasets
.hasOwnProperty(name
)) continue;
106 var series
= this.datasets
[name
];
107 if (series
.length
> 1) {
108 var x1
= series
[0][0];
109 if (!this.minxval
|| x1
< this.minxval
) this.minxval
= x1
;
111 var x2
= series
[series
.length
- 1][0];
112 if (!this.maxxval
|| x2
> this.maxxval
) this.maxxval
= x2
;
116 this.xrange
= this.maxxval
- this.minxval
;
117 this.xscale
= (this.xrange
!= 0 ? 1/this.xrange
: 1.0);
119 for (var i
= 0; i
< this.yAxes_
.length
; i
++) {
120 var axis
= this.yAxes_
[i
];
121 axis
.minyval
= axis
.computedValueRange
[0];
122 axis
.maxyval
= axis
.computedValueRange
[1];
123 axis
.yrange
= axis
.maxyval
- axis
.minyval
;
124 axis
.yscale
= (axis
.yrange
!= 0 ? 1.0 / axis
.yrange
: 1.0);
126 if (axis
.g
.attr_("logscale")) {
127 axis
.ylogrange
= Dygraph
.log10(axis
.maxyval
) - Dygraph
.log10(axis
.minyval
);
128 axis
.ylogscale
= (axis
.ylogrange
!= 0 ? 1.0 / axis
.ylogrange
: 1.0);
129 if (!isFinite(axis
.ylogrange
) || isNaN(axis
.ylogrange
)) {
130 axis
.g
.error('axis ' + i
+ ' of graph at ' + axis
.g
+
131 ' can\'t be displayed in log scale for range [' +
132 axis
.minyval
+ ' - ' + axis
.maxyval
+ ']');
138 DygraphLayout
.prototype._evaluateLineCharts
= function() {
140 this.points
= new Array();
141 for (var setName
in this.datasets
) {
142 if (!this.datasets
.hasOwnProperty(setName
)) continue;
144 var dataset
= this.datasets
[setName
];
145 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
147 for (var j
= 0; j
< dataset
.length
; j
++) {
148 var item
= dataset
[j
];
152 yval
= 1.0 - ((Dygraph
.log10(parseFloat(item
[1])) - Dygraph
.log10(axis
.minyval
)) * axis
.ylogscale
); // really should just be yscale.
154 yval
= 1.0 - ((parseFloat(item
[1]) - axis
.minyval
) * axis
.yscale
);
158 x
: ((parseFloat(item
[0]) - this.minxval
) * this.xscale
),
160 xval
: parseFloat(item
[0]),
161 yval
: parseFloat(item
[1]),
165 this.points
.push(point
);
170 DygraphLayout
.prototype._evaluateLineTicks
= function() {
171 this.xticks
= new Array();
172 for (var i
= 0; i
< this.xTicks_
.length
; i
++) {
173 var tick
= this.xTicks_
[i
];
174 var label
= tick
.label
;
175 var pos
= this.xscale
* (tick
.v
- this.minxval
);
176 if ((pos
>= 0.0) && (pos
<= 1.0)) {
177 this.xticks
.push([pos
, label
]);
181 this.yticks
= new Array();
182 for (var i
= 0; i
< this.yAxes_
.length
; i
++ ) {
183 var axis
= this.yAxes_
[i
];
184 for (var j
= 0; j
< axis
.ticks
.length
; j
++) {
185 var tick
= axis
.ticks
[j
];
186 var label
= tick
.label
;
187 var pos
= this.dygraph_
.toPercentYCoord(tick
.v
, i
);
188 if ((pos
>= 0.0) && (pos
<= 1.0)) {
189 this.yticks
.push([i
, pos
, label
]);
197 * Behaves the same way as PlotKit.Layout, but also copies the errors
200 DygraphLayout
.prototype.evaluateWithError
= function() {
202 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
204 // Copy over the error terms
205 var i
= 0; // index in this.points
206 for (var setName
in this.datasets
) {
207 if (!this.datasets
.hasOwnProperty(setName
)) continue;
209 var dataset
= this.datasets
[setName
];
210 for (var j
= 0; j
< dataset
.length
; j
++, i
++) {
211 var item
= dataset
[j
];
212 var xv
= parseFloat(item
[0]);
213 var yv
= parseFloat(item
[1]);
215 if (xv
== this.points
[i
].xval
&&
216 yv
== this.points
[i
].yval
) {
217 this.points
[i
].errorMinus
= parseFloat(item
[2]);
218 this.points
[i
].errorPlus
= parseFloat(item
[3]);
224 DygraphLayout
.prototype._evaluateAnnotations
= function() {
225 // Add the annotations to the point to which they belong.
226 // Make a map from (setName, xval) to annotation for quick lookups.
227 var annotations
= {};
228 for (var i
= 0; i
< this.annotations
.length
; i
++) {
229 var a
= this.annotations
[i
];
230 annotations
[a
.xval
+ "," + a
.series
] = a
;
233 this.annotated_points
= [];
234 for (var i
= 0; i
< this.points
.length
; i
++) {
235 var p
= this.points
[i
];
236 var k
= p
.xval
+ "," + p
.name
;
237 if (k
in annotations
) {
238 p
.annotation
= annotations
[k
];
239 this.annotated_points
.push(p
);
245 * Convenience function to remove all the data sets from a graph
247 DygraphLayout
.prototype.removeAllDatasets
= function() {
248 delete this.datasets
;
249 this.datasets
= new Array();
253 * Return a copy of the point at the indicated index, with its yval unstacked.
254 * @param int index of point in layout_.points
256 DygraphLayout
.prototype.unstackPointAtIndex
= function(idx
) {
257 var point
= this.points
[idx
];
259 // Clone the point since we modify it
260 var unstackedPoint
= {};
261 for (var i
in point
) {
262 unstackedPoint
[i
] = point
[i
];
265 if (!this.attr_("stackedGraph")) {
266 return unstackedPoint
;
269 // The unstacked yval is equal to the current yval minus the yval of the
270 // next point at the same xval.
271 for (var i
= idx
+1; i
< this.points
.length
; i
++) {
272 if (this.points
[i
].xval
== point
.xval
) {
273 unstackedPoint
.yval
-= this.points
[i
].yval
;
278 return unstackedPoint
;
282 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
283 * a canvas. It's based on PlotKit.CanvasRenderer.
284 * @param {Object} element The canvas to attach to
285 * @param {Object} elementContext The 2d context of the canvas (injected so it
286 * can be mocked for testing.)
287 * @param {Layout} layout The DygraphLayout object for this graph.
289 DygraphCanvasRenderer
= function(dygraph
, element
, elementContext
, layout
) {
290 this.dygraph_
= dygraph
;
292 this.layout
= layout
;
293 this.element
= element
;
294 this.elementContext
= elementContext
;
295 this.container
= this.element
.parentNode
;
297 this.height
= this.element
.height
;
298 this.width
= this.element
.width
;
300 // --- check whether everything is ok before we return
301 if (!this.isIE
&& !(DygraphCanvasRenderer
.isSupported(this.element
)))
302 throw "Canvas is not supported.";
305 this.xlabels
= new Array();
306 this.ylabels
= new Array();
307 this.annotations
= new Array();
308 this.chartLabels
= {};
310 this.area
= this.computeArea_();
311 this.container
.style
.position
= "relative";
312 this.container
.style
.width
= this.width
+ "px";
314 // Set up a clipping area for the canvas (and the interaction canvas).
315 // This ensures that we don't overdraw.
316 var ctx
= this.dygraph_
.canvas_ctx_
;
318 ctx
.rect(this.area
.x
, this.area
.y
, this.area
.w
, this.area
.h
);
321 ctx
= this.dygraph_
.hidden_ctx_
;
323 ctx
.rect(this.area
.x
, this.area
.y
, this.area
.w
, this.area
.h
);
327 DygraphCanvasRenderer
.prototype.attr_
= function(x
) {
328 return this.dygraph_
.attr_(x
);
331 // Compute the box which the chart should be drawn in. This is the canvas's
332 // box, less space needed for axis and chart labels.
333 // TODO(danvk): this belongs in DygraphLayout.
334 DygraphCanvasRenderer
.prototype.computeArea_
= function() {
336 // TODO(danvk): per-axis setting.
337 x
: this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize'),
340 area
.w
= this.width
- area
.x
- this.attr_('rightGap');
341 area
.h
= this.height
- this.attr_('axisLabelFontSize') -
342 2 * this.attr_('axisTickSize');
344 // Shrink the drawing area to accomodate additional y-axes.
345 if (this.dygraph_
.numAxes() == 2) {
346 // TODO(danvk): per-axis setting.
347 area
.w
-= (this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize'));
348 } else if (this.dygraph_
.numAxes() > 2) {
349 this.dygraph_
.error("Only two y-axes are supported at this time. (Trying " +
350 "to use " + this.dygraph_
.numAxes() + ")");
353 // Add space for chart labels: title, xlabel and ylabel.
354 if (this.attr_('title')) {
355 area
.h
-= this.attr_('titleHeight');
356 area
.y
+= this.attr_('titleHeight');
358 if (this.attr_('xlabel')) {
359 area
.h
-= this.attr_('xLabelHeight');
361 if (this.attr_('ylabel')) {
362 // It would make sense to shift the chart here to make room for the y-axis
363 // label, but the default yAxisLabelWidth is large enough that this results
364 // in overly-padded charts. The y-axis label should fit fine. If it
365 // doesn't, the yAxisLabelWidth option can be increased.
371 DygraphCanvasRenderer
.prototype.clear
= function() {
373 // VML takes a while to start up, so we just poll every this.IEDelay
375 if (this.clearDelay
) {
376 this.clearDelay
.cancel();
377 this.clearDelay
= null;
379 var context
= this.elementContext
;
382 // TODO(danvk): this is broken, since MochiKit.Async is gone.
383 this.clearDelay
= MochiKit
.Async
.wait(this.IEDelay
);
384 this.clearDelay
.addCallback(bind(this.clear
, this));
389 var context
= this.elementContext
;
390 context
.clearRect(0, 0, this.width
, this.height
);
392 for (var i
= 0; i
< this.xlabels
.length
; i
++) {
393 var el
= this.xlabels
[i
];
394 if (el
.parentNode
) el
.parentNode
.removeChild(el
);
396 for (var i
= 0; i
< this.ylabels
.length
; i
++) {
397 var el
= this.ylabels
[i
];
398 if (el
.parentNode
) el
.parentNode
.removeChild(el
);
400 for (var i
= 0; i
< this.annotations
.length
; i
++) {
401 var el
= this.annotations
[i
];
402 if (el
.parentNode
) el
.parentNode
.removeChild(el
);
404 for (var k
in this.chartLabels
) {
405 if (!this.chartLabels
.hasOwnProperty(k
)) continue;
406 var el
= this.chartLabels
[k
];
407 if (el
.parentNode
) el
.parentNode
.removeChild(el
);
409 this.xlabels
= new Array();
410 this.ylabels
= new Array();
411 this.annotations
= new Array();
412 this.chartLabels
= {};
416 DygraphCanvasRenderer
.isSupported
= function(canvasName
) {
419 if (typeof(canvasName
) == 'undefined' || canvasName
== null)
420 canvas
= document
.createElement("canvas");
423 var context
= canvas
.getContext("2d");
426 var ie
= navigator
.appVersion
.match(/MSIE (\d\.\d)/);
427 var opera
= (navigator
.userAgent
.toLowerCase().indexOf("opera") != -1);
428 if ((!ie
) || (ie
[1] < 6) || (opera
))
436 * Draw an X/Y grid on top of the existing plot
438 DygraphCanvasRenderer
.prototype.render
= function() {
439 // Draw the new X/Y grid
. Lines appear crisper when pixels are rounded to
440 // half-integers. This prevents them from drawing in two rows/cols.
441 var ctx
= this.elementContext
;
442 function halfUp(x
){return Math
.round(x
)+0.5};
443 function halfDown(y
){return Math
.round(y
)-0.5};
445 if (this.attr_('underlayCallback')) {
446 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
447 // users who expect a deprecated form of this callback.
448 this.attr_('underlayCallback')(ctx
, this.area
, this.dygraph_
, this.dygraph_
);
451 if (this.attr_('drawYGrid')) {
452 var ticks
= this.layout
.yticks
;
454 ctx
.strokeStyle
= this.attr_('gridLineColor');
455 ctx
.lineWidth
= this.attr_('axisLineWidth');
456 for (var i
= 0; i
< ticks
.length
; i
++) {
457 // TODO(danvk): allow secondary axes to draw a grid, too.
458 if (ticks
[i
][0] != 0) continue;
459 var x
= halfUp(this.area
.x
);
460 var y
= halfDown(this.area
.y
+ ticks
[i
][1] * this.area
.h
);
463 ctx
.lineTo(x
+ this.area
.w
, y
);
469 if (this.attr_('drawXGrid')) {
470 var ticks
= this.layout
.xticks
;
472 ctx
.strokeStyle
= this.attr_('gridLineColor');
473 ctx
.lineWidth
= this.attr_('axisLineWidth');
474 for (var i
=0; i
<ticks
.length
; i
++) {
475 var x
= halfUp(this.area
.x
+ ticks
[i
][0] * this.area
.w
);
476 var y
= halfDown(this.area
.y
+ this.area
.h
);
479 ctx
.lineTo(x
, this.area
.y
);
485 // Do the ordinary rendering, as before
486 this._renderLineChart();
488 this._renderChartLabels();
489 this._renderAnnotations();
493 DygraphCanvasRenderer
.prototype._renderAxis
= function() {
494 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
496 // Round pixels to half-integer boundaries for crisper drawing.
497 function halfUp(x
){return Math
.round(x
)+0.5};
498 function halfDown(y
){return Math
.round(y
)-0.5};
500 var context
= this.elementContext
;
503 position
: "absolute",
504 fontSize
: this.attr_('axisLabelFontSize') + "px",
506 color
: this.attr_('axisLabelColor'),
507 width
: this.attr_('axisLabelWidth') + "px",
510 var makeDiv
= function(txt
) {
511 var div
= document
.createElement("div");
512 for (var name
in labelStyle
) {
513 if (labelStyle
.hasOwnProperty(name
)) {
514 div
.style
[name
] = labelStyle
[name
];
517 div
.appendChild(document
.createTextNode(txt
));
523 context
.strokeStyle
= this.attr_('axisLineColor');
524 context
.lineWidth
= this.attr_('axisLineWidth');
526 if (this.attr_('drawYAxis')) {
527 if (this.layout
.yticks
&& this.layout
.yticks
.length
> 0) {
528 for (var i
= 0; i
< this.layout
.yticks
.length
; i
++) {
529 var tick
= this.layout
.yticks
[i
];
530 if (typeof(tick
) == "function") return;
533 if (tick
[0] == 1) { // right-side y-axis
534 x
= this.area
.x
+ this.area
.w
;
537 var y
= this.area
.y
+ tick
[1] * this.area
.h
;
539 context
.moveTo(halfUp(x
), halfDown(y
));
540 context
.lineTo(halfUp(x
- sgn
* this.attr_('axisTickSize')), halfDown(y
));
544 var label
= makeDiv(tick
[2]);
545 var top
= (y
- this.attr_('axisLabelFontSize') / 2);
546 if (top
< 0) top
= 0;
548 if (top
+ this.attr_('axisLabelFontSize') + 3 > this.height
) {
549 label
.style
.bottom
= "0px";
551 label
.style
.top
= top
+ "px";
554 label
.style
.left
= (this.area
.x
- this.attr_('yAxisLabelWidth') - this.attr_('axisTickSize')) + "px";
555 label
.style
.textAlign
= "right";
556 } else if (tick
[0] == 1) {
557 label
.style
.left
= (this.area
.x
+ this.area
.w
+
558 this.attr_('axisTickSize')) + "px";
559 label
.style
.textAlign
= "left";
561 label
.style
.width
= this.attr_('yAxisLabelWidth') + "px";
562 this.container
.appendChild(label
);
563 this.ylabels
.push(label
);
566 // The lowest tick on the y-axis often overlaps with the leftmost
567 // tick on the x-axis. Shift the bottom tick up a little bit to
568 // compensate if necessary.
569 var bottomTick
= this.ylabels
[0];
570 var fontSize
= this.attr_('axisLabelFontSize');
571 var bottom
= parseInt(bottomTick
.style
.top
) + fontSize
;
572 if (bottom
> this.height
- fontSize
) {
573 bottomTick
.style
.top
= (parseInt(bottomTick
.style
.top
) -
574 fontSize
/ 2) + "px";
578 // draw a vertical line on the left to separate the chart from the labels.
580 context
.moveTo(halfUp(this.area
.x
), halfDown(this.area
.y
));
581 context
.lineTo(halfUp(this.area
.x
), halfDown(this.area
.y
+ this.area
.h
));
585 // if there's a secondary y-axis, draw a vertical line for that, too.
586 if (this.dygraph_
.numAxes() == 2) {
588 context
.moveTo(halfDown(this.area
.x
+ this.area
.w
), halfDown(this.area
.y
));
589 context
.lineTo(halfDown(this.area
.x
+ this.area
.w
), halfDown(this.area
.y
+ this.area
.h
));
595 if (this.attr_('drawXAxis')) {
596 if (this.layout
.xticks
) {
597 for (var i
= 0; i
< this.layout
.xticks
.length
; i
++) {
598 var tick
= this.layout
.xticks
[i
];
599 if (typeof(dataset
) == "function") return;
601 var x
= this.area
.x
+ tick
[0] * this.area
.w
;
602 var y
= this.area
.y
+ this.area
.h
;
604 context
.moveTo(halfUp(x
), halfDown(y
));
605 context
.lineTo(halfUp(x
), halfDown(y
+ this.attr_('axisTickSize')));
609 var label
= makeDiv(tick
[1]);
610 label
.style
.textAlign
= "center";
611 label
.style
.top
= (y
+ this.attr_('axisTickSize')) + 'px';
613 var left
= (x
- this.attr_('axisLabelWidth')/2);
614 if (left
+ this.attr_('axisLabelWidth') > this.width
) {
615 left
= this.width
- this.attr_('xAxisLabelWidth');
616 label
.style
.textAlign
= "right";
620 label
.style
.textAlign
= "left";
623 label
.style
.left
= left
+ "px";
624 label
.style
.width
= this.attr_('xAxisLabelWidth') + "px";
625 this.container
.appendChild(label
);
626 this.xlabels
.push(label
);
631 context
.moveTo(halfUp(this.area
.x
), halfDown(this.area
.y
+ this.area
.h
));
632 context
.lineTo(halfUp(this.area
.x
+ this.area
.w
), halfDown(this.area
.y
+ this.area
.h
));
641 DygraphCanvasRenderer
.prototype._renderChartLabels
= function() {
642 // Generate divs for the chart title, xlabel and ylabel.
643 // Space for these divs has already been taken away from the charting area in
644 // the DygraphCanvasRenderer constructor.
645 if (this.attr_('title')) {
646 var div
= document
.createElement("div");
647 div
.style
.position
= 'absolute';
648 div
.style
.top
= '0px';
649 div
.style
.left
= this.area
.x
+ 'px';
650 div
.style
.width
= this.area
.w
+ 'px';
651 div
.style
.height
= this.attr_('titleHeight') + 'px';
652 div
.style
.textAlign
= 'center';
653 div
.style
.fontSize
= (this.attr_('titleHeight') - 8) + 'px';
654 div
.style
.fontWeight
= 'bold';
655 var class_div
= document
.createElement("div");
656 class_div
.className
= 'dygraph-label dygraph-title';
657 class_div
.innerHTML
= this.attr_('title');
658 div
.appendChild(class_div
);
659 this.container
.appendChild(div
);
660 this.chartLabels
.title
= div
;
663 if (this.attr_('xlabel')) {
664 var div
= document
.createElement("div");
665 div
.style
.position
= 'absolute';
666 div
.style
.bottom
= 0; // TODO(danvk): this is lazy. Calculate style.top.
667 div
.style
.left
= this.area
.x
+ 'px';
668 div
.style
.width
= this.area
.w
+ 'px';
669 div
.style
.height
= this.attr_('xLabelHeight') + 'px';
670 div
.style
.textAlign
= 'center';
671 div
.style
.fontSize
= (this.attr_('xLabelHeight') - 2) + 'px';
673 var class_div
= document
.createElement("div");
674 class_div
.className
= 'dygraph-label dygraph-xlabel';
675 class_div
.innerHTML
= this.attr_('xlabel');
676 div
.appendChild(class_div
);
677 this.container
.appendChild(div
);
678 this.chartLabels
.xlabel
= div
;
681 if (this.attr_('ylabel')) {
685 width
: this.attr_('yLabelWidth'),
688 // TODO(danvk): is this outer div actually necessary?
689 var div
= document
.createElement("div");
690 div
.style
.position
= 'absolute';
691 div
.style
.left
= box
.left
;
692 div
.style
.top
= box
.top
+ 'px';
693 div
.style
.width
= box
.width
+ 'px';
694 div
.style
.height
= box
.height
+ 'px';
695 div
.style
.fontSize
= (this.attr_('yLabelWidth') - 2) + 'px';
697 var inner_div
= document
.createElement("div");
698 inner_div
.style
.position
= 'absolute';
699 inner_div
.style
.width
= box
.height
+ 'px';
700 inner_div
.style
.height
= box
.width
+ 'px';
701 inner_div
.style
.top
= (box
.height
/ 2 - box.width / 2) + 'px';
702 inner_div
.style
.left
= (box
.width
/ 2 - box.height / 2) + 'px';
703 inner_div
.style
.textAlign
= 'center';
705 // CSS rotation is an HTML5 feature which is not standardized. Hence every
706 // browser has its own name for the CSS style.
707 inner_div
.style
.transform
= 'rotate(-90deg)'; // HTML5
708 inner_div
.style
.WebkitTransform
= 'rotate(-90deg)'; // Safari/Chrome
709 inner_div
.style
.MozTransform
= 'rotate(-90deg)'; // Firefox
710 inner_div
.style
.OTransform
= 'rotate(-90deg)'; // Opera
711 inner_div
.style
.msTransform
= 'rotate(-90deg)'; // IE9
713 if (typeof(document
.documentMode
) !== 'undefined' &&
714 document
.documentMode
< 9) {
715 // We're dealing w/ an old version of IE
, so we have to rotate the text
716 // using a BasicImage transform. This uses a different origin of rotation
717 // than HTML5 rotation (top left of div vs. its center).
718 inner_div
.style
.filter
=
719 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
720 inner_div
.style
.left
= '0px';
721 inner_div
.style
.top
= '0px';
724 var class_div
= document
.createElement("div");
725 class_div
.className
= 'dygraph-label dygraph-ylabel';
726 class_div
.innerHTML
= this.attr_('ylabel');
728 inner_div
.appendChild(class_div
);
729 div
.appendChild(inner_div
);
730 this.container
.appendChild(div
);
731 this.chartLabels
.ylabel
= div
;
736 DygraphCanvasRenderer
.prototype._renderAnnotations
= function() {
737 var annotationStyle
= {
738 "position": "absolute",
739 "fontSize": this.attr_('axisLabelFontSize') + "px",
744 var bindEvt
= function(eventName
, classEventName
, p
, self
) {
746 var a
= p
.annotation
;
747 if (a
.hasOwnProperty(eventName
)) {
748 a
[eventName
](a
, p
, self
.dygraph_
, e
);
749 } else if (self
.dygraph_
.attr_(classEventName
)) {
750 self
.dygraph_
.attr_(classEventName
)(a
, p
, self
.dygraph_
,e
);
755 // Get a list of point with annotations.
756 var points
= this.layout
.annotated_points
;
757 for (var i
= 0; i
< points
.length
; i
++) {
759 if (p
.canvasx
< this.area
.x
|| p
.canvasx
> this.area
.x
+ this.area
.w
) {
763 var a
= p
.annotation
;
765 if (a
.hasOwnProperty("tickHeight")) {
766 tick_height
= a
.tickHeight
;
769 var div
= document
.createElement("div");
770 for (var name
in annotationStyle
) {
771 if (annotationStyle
.hasOwnProperty(name
)) {
772 div
.style
[name
] = annotationStyle
[name
];
775 if (!a
.hasOwnProperty('icon')) {
776 div
.className
= "dygraphDefaultAnnotation";
778 if (a
.hasOwnProperty('cssClass')) {
779 div
.className
+= " " + a
.cssClass
;
782 var width
= a
.hasOwnProperty('width') ? a
.width
: 16;
783 var height
= a
.hasOwnProperty('height') ? a
.height
: 16;
784 if (a
.hasOwnProperty('icon')) {
785 var img
= document
.createElement("img");
789 div
.appendChild(img
);
790 } else if (p
.annotation
.hasOwnProperty('shortText')) {
791 div
.appendChild(document
.createTextNode(p
.annotation
.shortText
));
793 div
.style
.left
= (p
.canvasx
- width
/ 2) + "px";
794 if (a
.attachAtBottom
) {
795 div
.style
.top
= (this.area
.h
- height
- tick_height
) + "px";
797 div
.style
.top
= (p
.canvasy
- height
- tick_height
) + "px";
799 div
.style
.width
= width
+ "px";
800 div
.style
.height
= height
+ "px";
801 div
.title
= p
.annotation
.text
;
802 div
.style
.color
= this.colors
[p
.name
];
803 div
.style
.borderColor
= this.colors
[p
.name
];
806 Dygraph
.addEvent(div
, 'click',
807 bindEvt('clickHandler', 'annotationClickHandler', p
, this));
808 Dygraph
.addEvent(div
, 'mouseover',
809 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p
, this));
810 Dygraph
.addEvent(div
, 'mouseout',
811 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p
, this));
812 Dygraph
.addEvent(div
, 'dblclick',
813 bindEvt('dblClickHandler', 'annotationDblClickHandler', p
, this));
815 this.container
.appendChild(div
);
816 this.annotations
.push(div
);
818 var ctx
= this.elementContext
;
819 ctx
.strokeStyle
= this.colors
[p
.name
];
821 if (!a
.attachAtBottom
) {
822 ctx
.moveTo(p
.canvasx
, p
.canvasy
);
823 ctx
.lineTo(p
.canvasx
, p
.canvasy
- 2 - tick_height
);
825 ctx
.moveTo(p
.canvasx
, this.area
.h
);
826 ctx
.lineTo(p
.canvasx
, this.area
.h
- 2 - tick_height
);
835 * Overrides the CanvasRenderer method to draw error bars
837 DygraphCanvasRenderer
.prototype._renderLineChart
= function() {
838 // TODO(danvk): use this.attr_ for many of these.
839 var context
= this.elementContext
;
840 var colorScheme
= this.attr_('colors');
841 var fillAlpha
= this.attr_('fillAlpha');
842 var errorBars
= this.attr_("errorBars");
843 var fillGraph
= this.attr_("fillGraph");
844 var stackedGraph
= this.attr_("stackedGraph");
845 var stepPlot
= this.attr_("stepPlot");
848 for (var name
in this.layout
.datasets
) {
849 if (this.layout
.datasets
.hasOwnProperty(name
)) {
853 var setCount
= setNames
.length
;
855 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
857 for (var i
= 0; i
< setCount
; i
++) {
858 this.colors
[setNames
[i
]] = colorScheme
[i
% colorScheme
.length
];
863 for (var i
= 0; i
< this.layout
.points
.length
; i
++) {
864 var point
= this.layout
.points
[i
];
865 point
.canvasx
= this.area
.w
* point
.x
+ this.area
.x
;
866 point
.canvasy
= this.area
.h
* point
.y
+ this.area
.y
;
873 this.dygraph_
.warn("Can't use fillGraph option with error bars");
876 for (var i
= 0; i
< setCount
; i
++) {
877 var setName
= setNames
[i
];
878 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
879 var color
= this.colors
[setName
];
881 // setup graphics context
885 var prevYs
= [-1, -1];
886 var yscale
= axis
.yscale
;
887 // should be same color as the lines but only 15% opaque.
888 var rgb
= new RGBColor(color
);
889 var err_color
= 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' +
891 ctx
.fillStyle
= err_color
;
893 for (var j
= 0; j
< this.layout
.points
.length
; j
++) {
894 var point
= this.layout
.points
[j
];
895 if (point
.name
== setName
) {
896 if (!Dygraph
.isOK(point
.y
)) {
903 var newYs
= [ prevY
- point
.errorPlus
* yscale
,
904 prevY
+ point
.errorMinus
* yscale
];
907 var newYs
= [ point
.y
- point
.errorPlus
* yscale
,
908 point
.y
+ point
.errorMinus
* yscale
];
910 newYs
[0] = this.area
.h
* newYs
[0] + this.area
.y
;
911 newYs
[1] = this.area
.h
* newYs
[1] + this.area
.y
;
914 ctx
.moveTo(prevX
, newYs
[0]);
916 ctx
.moveTo(prevX
, prevYs
[0]);
918 ctx
.lineTo(point
.canvasx
, newYs
[0]);
919 ctx
.lineTo(point
.canvasx
, newYs
[1]);
921 ctx
.lineTo(prevX
, newYs
[1]);
923 ctx
.lineTo(prevX
, prevYs
[1]);
928 prevX
= point
.canvasx
;
933 } else if (fillGraph
) {
934 var baseline
= [] // for stacked graphs: baseline for filling
936 // process sets in reverse order (needed for stacked graphs)
937 for (var i
= setCount
- 1; i
>= 0; i
--) {
938 var setName
= setNames
[i
];
939 var color
= this.colors
[setName
];
940 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
941 var axisY
= 1.0 + axis
.minyval
* axis
.yscale
;
942 if (axisY
< 0.0) axisY
= 0.0;
943 else if (axisY
> 1.0) axisY
= 1.0;
944 axisY
= this.area
.h
* axisY
+ this.area
.y
;
946 // setup graphics context
949 var prevYs
= [-1, -1];
950 var yscale
= axis
.yscale
;
951 // should be same color as the lines but only 15% opaque.
952 var rgb
= new RGBColor(color
);
953 var err_color
= 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' +
955 ctx
.fillStyle
= err_color
;
957 for (var j
= 0; j
< this.layout
.points
.length
; j
++) {
958 var point
= this.layout
.points
[j
];
959 if (point
.name
== setName
) {
960 if (!Dygraph
.isOK(point
.y
)) {
966 lastY
= baseline
[point
.canvasx
];
967 if (lastY
=== undefined
) lastY
= axisY
;
968 baseline
[point
.canvasx
] = point
.canvasy
;
969 newYs
= [ point
.canvasy
, lastY
];
971 newYs
= [ point
.canvasy
, axisY
];
974 ctx
.moveTo(prevX
, prevYs
[0]);
976 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
978 ctx
.lineTo(point
.canvasx
, newYs
[0]);
980 ctx
.lineTo(point
.canvasx
, newYs
[1]);
981 ctx
.lineTo(prevX
, prevYs
[1]);
985 prevX
= point
.canvasx
;
992 for (var i
= 0; i
< setCount
; i
++) {
993 var setName
= setNames
[i
];
994 var color
= this.colors
[setName
];
995 var strokeWidth
= this.dygraph_
.attr_("strokeWidth", setName
);
997 // setup graphics context
999 var point
= this.layout
.points
[0];
1000 var pointSize
= this.dygraph_
.attr_("pointSize", setName
);
1001 var prevX
= null, prevY
= null;
1002 var drawPoints
= this.dygraph_
.attr_("drawPoints", setName
);
1003 var points
= this.layout
.points
;
1004 for (var j
= 0; j
< points
.length
; j
++) {
1005 var point
= points
[j
];
1006 if (point
.name
== setName
) {
1007 if (!Dygraph
.isOK(point
.canvasy
)) {
1008 if (stepPlot
&& prevX
!= null) {
1009 // Draw a horizontal line to the start of the missing data
1011 ctx
.strokeStyle
= color
;
1012 ctx
.lineWidth
= this.attr_('strokeWidth');
1013 ctx
.moveTo(prevX
, prevY
);
1014 ctx
.lineTo(point
.canvasx
, prevY
);
1017 // this will make us move to the next point, not draw a line to it.
1018 prevX
= prevY
= null;
1020 // A point is "isolated" if it is non-null but both the previous
1021 // and next points are null.
1022 var isIsolated
= (!prevX
&& (j
== points
.length
- 1 ||
1023 !Dygraph
.isOK(points
[j
+1].canvasy
)));
1026 prevX
= point
.canvasx
;
1027 prevY
= point
.canvasy
;
1029 // TODO(danvk): figure out why this conditional is necessary.
1032 ctx
.strokeStyle
= color
;
1033 ctx
.lineWidth
= strokeWidth
;
1034 ctx
.moveTo(prevX
, prevY
);
1036 ctx
.lineTo(point
.canvasx
, prevY
);
1038 prevX
= point
.canvasx
;
1039 prevY
= point
.canvasy
;
1040 ctx
.lineTo(prevX
, prevY
);
1045 if (drawPoints
|| isIsolated
) {
1047 ctx
.fillStyle
= color
;
1048 ctx
.arc(point
.canvasx
, point
.canvasy
, pointSize
,
1049 0, 2 * Math
.PI
, false);