beef2c03b39c2270335c0eba3a399801f4d2f09b
[dygraphs.git] / dygraph-canvas.js
1 // Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2 // All Rights Reserved.
3
4 /**
5 * @fileoverview Subclasses various parts of PlotKit to meet the additional
6 * needs of Dygraph: grid overlays and error bars
7 */
8
9 // Subclass PlotKit.Layout to add:
10 // 1. Sigma/errorBars properties
11 // 2. Copy error terms for PlotKit.CanvasRenderer._renderLineChart
12
13 /**
14 * Creates a new DygraphLayout object. Options are the same as those allowed
15 * by the PlotKit.Layout constructor.
16 * @param {Object} options Options for PlotKit.Layout
17 * @return {Object} The DygraphLayout object
18 */
19 DygraphLayout = function(dygraph, options) {
20 this.dygraph_ = dygraph;
21 this.options = {}; // TODO(danvk): remove, use attr_ instead.
22 MochiKit.Base.update(this.options, options ? options : {});
23 this.datasets = new Array();
24 };
25
26 DygraphLayout.prototype.attr_ = function(name) {
27 return this.dygraph_.attr_(name);
28 };
29
30 DygraphLayout.prototype.addDataset = function(setname, set_xy) {
31 this.datasets[setname] = set_xy;
32 };
33
34 DygraphLayout.prototype.evaluate = function() {
35 this._evaluateLimits();
36 this._evaluateLineCharts();
37 this._evaluateLineTicks();
38 };
39
40 DygraphLayout.prototype._evaluateLimits = function() {
41 this.minxval = this.maxxval = null;
42 for (var name in this.datasets) {
43 var series = this.datasets[name];
44 var x1 = series[0][0];
45 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
46
47 var x2 = series[series.length - 1][0];
48 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
49 }
50 this.xrange = this.maxxval - this.minxval;
51 this.xscale = (this.xrange != 0 ? 1/this.xrange : 1.0);
52
53 this.minyval = this.options.yAxis[0];
54 this.maxyval = this.options.yAxis[1];
55 this.yrange = this.maxyval - this.minyval;
56 this.yscale = (this.yrange != 0 ? 1/this.yrange : 1.0);
57 };
58
59 DygraphLayout.prototype._evaluateLineCharts = function() {
60 // add all the rects
61 this.points = new Array();
62 for (var setName in this.datasets) {
63 var dataset = this.datasets[setName];
64 for (var j = 0; j < dataset.length; j++) {
65 var item = dataset[j];
66 var point = {
67 x: ((parseFloat(item[0]) - this.minxval) * this.xscale),
68 y: 1.0 - ((parseFloat(item[1]) - this.minyval) * this.yscale),
69 xval: parseFloat(item[0]),
70 yval: parseFloat(item[1]),
71 name: setName
72 };
73
74 // limit the x, y values so they do not overdraw
75 if (point.y <= 0.0) {
76 point.y = 0.0;
77 }
78 if (point.y >= 1.0) {
79 point.y = 1.0;
80 }
81 if ((point.x >= 0.0) && (point.x <= 1.0)) {
82 this.points.push(point);
83 }
84 }
85 }
86 };
87
88 DygraphLayout.prototype._evaluateLineTicks = function() {
89 this.xticks = new Array();
90 for (var i = 0; i < this.options.xTicks.length; i++) {
91 var tick = this.options.xTicks[i];
92 var label = tick.label;
93 var pos = this.xscale * (tick.v - this.minxval);
94 if ((pos >= 0.0) && (pos <= 1.0)) {
95 this.xticks.push([pos, label]);
96 }
97 }
98
99 this.yticks = new Array();
100 for (var i = 0; i < this.options.yTicks.length; i++) {
101 var tick = this.options.yTicks[i];
102 var label = tick.label;
103 var pos = 1.0 - (this.yscale * (tick.v - this.minyval));
104 if ((pos >= 0.0) && (pos <= 1.0)) {
105 this.yticks.push([pos, label]);
106 }
107 }
108 };
109
110
111 /**
112 * Behaves the same way as PlotKit.Layout, but also copies the errors
113 * @private
114 */
115 DygraphLayout.prototype.evaluateWithError = function() {
116 this.evaluate();
117 if (!this.options.errorBars) return;
118
119 // Copy over the error terms
120 var i = 0; // index in this.points
121 for (var setName in this.datasets) {
122 var j = 0;
123 var dataset = this.datasets[setName];
124 if (PlotKit.Base.isFuncLike(dataset)) continue;
125 for (var j = 0; j < dataset.length; j++, i++) {
126 var item = dataset[j];
127 var xv = parseFloat(item[0]);
128 var yv = parseFloat(item[1]);
129
130 if (xv == this.points[i].xval &&
131 yv == this.points[i].yval) {
132 this.points[i].errorMinus = parseFloat(item[2]);
133 this.points[i].errorPlus = parseFloat(item[3]);
134 }
135 }
136 }
137 };
138
139 /**
140 * Convenience function to remove all the data sets from a graph
141 */
142 DygraphLayout.prototype.removeAllDatasets = function() {
143 delete this.datasets;
144 this.datasets = new Array();
145 };
146
147 /**
148 * Change the values of various layout options
149 * @param {Object} new_options an associative array of new properties
150 */
151 DygraphLayout.prototype.updateOptions = function(new_options) {
152 MochiKit.Base.update(this.options, new_options ? new_options : {});
153 };
154
155 // Subclass PlotKit.CanvasRenderer to add:
156 // 1. X/Y grid overlay
157 // 2. Ability to draw error bars (if required)
158
159 /**
160 * Sets some PlotKit.CanvasRenderer options
161 * @param {Object} element The canvas to attach to
162 * @param {Layout} layout The DygraphLayout object for this graph.
163 * @param {Object} options Options to pass on to CanvasRenderer
164 */
165 DygraphCanvasRenderer = function(dygraph, element, layout, options) {
166 // TODO(danvk): remove options, just use dygraph.attr_.
167 PlotKit.CanvasRenderer.call(this, element, layout, options);
168 this.dygraph_ = dygraph;
169 this.options.drawYGrid = true;
170 this.options.drawXGrid = true;
171 this.options.gridLineColor = MochiKit.Color.Color.grayColor();
172 MochiKit.Base.update(this.options, options);
173
174 // TODO(danvk) This shouldn't be necessary: effects should be overlaid
175 this.options.drawBackground = false;
176 };
177 DygraphCanvasRenderer.prototype = new PlotKit.CanvasRenderer();
178
179 /**
180 * Draw an X/Y grid on top of the existing plot
181 */
182 DygraphCanvasRenderer.prototype.render = function() {
183 // Draw the new X/Y grid
184 var ctx = this.element.getContext("2d");
185 if (this.options.drawYGrid) {
186 var ticks = this.layout.yticks;
187 ctx.save();
188 ctx.strokeStyle = this.options.gridLineColor.toRGBString();
189 ctx.lineWidth = this.options.axisLineWidth;
190 for (var i = 0; i < ticks.length; i++) {
191 var x = this.area.x;
192 var y = this.area.y + ticks[i][0] * this.area.h;
193 ctx.beginPath();
194 ctx.moveTo(x, y);
195 ctx.lineTo(x + this.area.w, y);
196 ctx.closePath();
197 ctx.stroke();
198 }
199 }
200
201 if (this.options.drawXGrid) {
202 var ticks = this.layout.xticks;
203 ctx.save();
204 ctx.strokeStyle = this.options.gridLineColor.toRGBString();
205 ctx.lineWidth = this.options.axisLineWidth;
206 for (var i=0; i<ticks.length; i++) {
207 var x = this.area.x + ticks[i][0] * this.area.w;
208 var y = this.area.y + this.area.h;
209 ctx.beginPath();
210 ctx.moveTo(x, y);
211 ctx.lineTo(x, this.area.y);
212 ctx.closePath();
213 ctx.stroke();
214 }
215 }
216
217 // Do the ordinary rendering, as before
218 // TODO(danvk) Call super.render()
219 this._renderLineChart();
220 this._renderLineAxis();
221 };
222
223 /**
224 * Overrides the CanvasRenderer method to draw error bars
225 */
226 DygraphCanvasRenderer.prototype._renderLineChart = function() {
227 var context = this.element.getContext("2d");
228 var colorCount = this.options.colorScheme.length;
229 var colorScheme = this.options.colorScheme;
230 var setNames = MochiKit.Base.keys(this.layout.datasets);
231 var errorBars = this.layout.options.errorBars;
232 var setCount = setNames.length;
233 var bind = MochiKit.Base.bind;
234 var partial = MochiKit.Base.partial;
235
236 //Update Points
237 var updatePoint = function(point) {
238 point.canvasx = this.area.w * point.x + this.area.x;
239 point.canvasy = this.area.h * point.y + this.area.y;
240 }
241 MochiKit.Iter.forEach(this.layout.points, updatePoint, this);
242
243 // create paths
244 var isOK = function(x) { return x && !isNaN(x); };
245 var makePath = function(ctx) {
246 for (var i = 0; i < setCount; i++) {
247 var setName = setNames[i];
248 var color = colorScheme[i%colorCount];
249 var strokeX = this.options.strokeColorTransform;
250
251 // setup graphics context
252 context.save();
253 context.strokeStyle = color.toRGBString();
254 context.lineWidth = this.options.strokeWidth;
255 var point = this.layout.points[0];
256 var pointSize = this.dygraph_.attr_("pointSize");
257 var prevX = null, prevY = null;
258 var drawPoints = this.dygraph_.attr_("drawPoints");
259 var points = this.layout.points;
260 for (var j = 0; j < points.length; j++) {
261 var point = points[j];
262 if (point.name == setName) {
263 if (!isOK(point.canvasy)) {
264 // this will make us move to the next point, not draw a line to it.
265 prevX = prevY = null;
266 } else {
267 // A point is "isolated" if it is non-null but both the previous
268 // and next points are null.
269 var isIsolated = (!prevX && (j == points.length - 1 ||
270 !isOK(points[j+1].canvasy)));
271
272 if (!prevX) {
273 prevX = point.canvasx;
274 prevY = point.canvasy;
275 } else {
276 ctx.beginPath();
277 ctx.moveTo(prevX, prevY);
278 prevX = point.canvasx;
279 prevY = point.canvasy;
280 ctx.lineTo(prevX, prevY);
281 ctx.stroke();
282 }
283
284 if (drawPoints || isIsolated) {
285 ctx.beginPath();
286 ctx.fillStyle = color.toRGBString();
287 ctx.arc(point.canvasx, point.canvasy, pointSize, 0, 360, false);
288 ctx.fill();
289 }
290 }
291 }
292 }
293 }
294 };
295
296 var makeErrorBars = function(ctx) {
297 for (var i = 0; i < setCount; i++) {
298 var setName = setNames[i];
299 var color = colorScheme[i % colorCount];
300 var strokeX = this.options.strokeColorTransform;
301
302 // setup graphics context
303 context.save();
304 context.strokeStyle = color.toRGBString();
305 context.lineWidth = this.options.strokeWidth;
306 var prevX = -1;
307 var prevYs = [-1, -1];
308 var count = 0;
309 var yscale = this.layout.yscale;
310 var errorTrapezoid = function(ctx_,point) {
311 count++;
312 if (point.name == setName) {
313 if (!point.y || isNaN(point.y)) {
314 prevX = -1;
315 return;
316 }
317 var newYs = [ point.y - point.errorPlus * yscale,
318 point.y + point.errorMinus * yscale ];
319 newYs[0] = this.area.h * newYs[0] + this.area.y;
320 newYs[1] = this.area.h * newYs[1] + this.area.y;
321 if (prevX >= 0) {
322 ctx_.moveTo(prevX, prevYs[0]);
323 ctx_.lineTo(point.canvasx, newYs[0]);
324 ctx_.lineTo(point.canvasx, newYs[1]);
325 ctx_.lineTo(prevX, prevYs[1]);
326 ctx_.closePath();
327 }
328 prevYs[0] = newYs[0];
329 prevYs[1] = newYs[1];
330 prevX = point.canvasx;
331 }
332 };
333 // should be same color as the lines
334 var err_color = color.colorWithAlpha(0.15);
335 ctx.fillStyle = err_color.toRGBString();
336 ctx.beginPath();
337 MochiKit.Iter.forEach(this.layout.points, partial(errorTrapezoid, ctx), this);
338 ctx.fill();
339 }
340 };
341
342 if (errorBars)
343 bind(makeErrorBars, this)(context);
344 bind(makePath, this)(context);
345 context.restore();
346 };