3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
8 * @fileoverview Based on PlotKitLayout, but modified to meet the needs of
12 /*jshint globalstrict: true */
13 /*global Dygraph:false */
17 * Creates a new DygraphLayout object.
19 * This class contains all the data to be charted.
20 * It uses data coordinates, but also records the chart range (in data
21 * coordinates) and hence is able to calculate percentage positions ('In this
22 * view, Point A lies 25% down the x-axis.')
24 * Two things that it does not do are:
25 * 1. Record pixel coordinates for anything.
26 * 2. (oddly) determine anything about the layout of chart elements.
28 * The naming is a vestige of Dygraph's original PlotKit roots.
32 var DygraphLayout
= function(dygraph
) {
33 this.dygraph_
= dygraph
;
36 this.annotations
= [];
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
.push(set_xy
);
52 this.setNames
.push(setname
);
56 * Returns the box which the chart should be drawn in. This is the canvas's
57 * box, less space needed for the axis and chart labels.
59 * @return {{x: number, y: number, w: number, h: number}}
61 DygraphLayout
.prototype.getPlotArea
= function() {
65 // Compute the box which the chart should be drawn in. This is the canvas's
66 // box, less space needed for axis, chart labels, and other plug-ins.
67 // NOTE: This should only be called by Dygraph.predraw_().
68 DygraphLayout
.prototype.computePlotArea
= function() {
70 // TODO(danvk): per-axis setting.
75 area
.w
= this.dygraph_
.width_
- area
.x
- this.attr_('rightGap');
76 area
.h
= this.dygraph_
.height_
;
78 // Let plugins reserve space.
80 chart_div
: this.dygraph_
.graphDiv
,
81 reserveSpaceLeft
: function(px
) {
92 reserveSpaceRight
: function(px
) {
94 x
: area
.x
+ area
.w
- px
,
102 reserveSpaceTop
: function(px
) {
113 reserveSpaceBottom
: function(px
) {
116 y
: area
.y
+ area
.h
- px
,
123 chartRect
: function() {
124 return {x
:area
.x
, y
:area
.y
, w
:area
.w
, h
:area
.h
};
127 this.dygraph_
.cascadeEvents_('layout', e
);
132 DygraphLayout
.prototype.setAnnotations
= function(ann
) {
133 // The Dygraph object's annotations aren't parsed. We parse them here and
134 // save a copy. If there is no parser, then the user must be using raw format.
135 this.annotations
= [];
136 var parse
= this.attr_('xValueParser') || function(x
) { return x
; };
137 for (var i
= 0; i
< ann
.length
; i
++) {
139 if (!ann
[i
].xval
&& ann
[i
].x
=== undefined
) {
140 this.dygraph_
.error("Annotations must have an 'x' property");
144 !(ann
[i
].hasOwnProperty('width') &&
145 ann
[i
].hasOwnProperty('height'))) {
146 this.dygraph_
.error("Must set width and height when setting " +
147 "annotation.icon property");
150 Dygraph
.update(a
, ann
[i
]);
151 if (!a
.xval
) a
.xval
= parse(a
.x
);
152 this.annotations
.push(a
);
156 DygraphLayout
.prototype.setXTicks
= function(xTicks
) {
157 this.xTicks_
= xTicks
;
160 // TODO(danvk): add this to the Dygraph object's API or move it into Layout.
161 DygraphLayout
.prototype.setYAxes
= function (yAxes
) {
165 DygraphLayout
.prototype.evaluate
= function() {
166 this._evaluateLimits();
167 this._evaluateLineCharts();
168 this._evaluateLineTicks();
169 this._evaluateAnnotations();
172 DygraphLayout
.prototype._evaluateLimits
= function() {
173 var xlimits
= this.dygraph_
.xAxisRange();
174 this.minxval
= xlimits
[0];
175 this.maxxval
= xlimits
[1];
176 var xrange
= xlimits
[1] - xlimits
[0];
177 this.xscale
= (xrange
!== 0 ? 1 / xrange
: 1.0);
179 for (var i
= 0; i
< this.yAxes_
.length
; i
++) {
180 var axis
= this.yAxes_
[i
];
181 axis
.minyval
= axis
.computedValueRange
[0];
182 axis
.maxyval
= axis
.computedValueRange
[1];
183 axis
.yrange
= axis
.maxyval
- axis
.minyval
;
184 axis
.yscale
= (axis
.yrange
!== 0 ? 1.0 / axis
.yrange
: 1.0);
186 if (axis
.g
.attr_("logscale")) {
187 axis
.ylogrange
= Dygraph
.log10(axis
.maxyval
) - Dygraph
.log10(axis
.minyval
);
188 axis
.ylogscale
= (axis
.ylogrange
!== 0 ? 1.0 / axis
.ylogrange
: 1.0);
189 if (!isFinite(axis
.ylogrange
) || isNaN(axis
.ylogrange
)) {
190 axis
.g
.error('axis ' + i
+ ' of graph at ' + axis
.g
+
191 ' can\'t be displayed in log scale for range [' +
192 axis
.minyval
+ ' - ' + axis
.maxyval
+ ']');
198 DygraphLayout
._calcYNormal
= function(axis
, value
, logscale
) {
200 return 1.0 - ((Dygraph
.log10(value
) - Dygraph
.log10(axis
.minyval
)) * axis
.ylogscale
);
202 return 1.0 - ((value
- axis
.minyval
) * axis
.yscale
);
206 DygraphLayout
.prototype._evaluateLineCharts
= function() {
207 var connectSeparated
= this.attr_('connectSeparatedPoints');
209 // series index -> point index in series -> |point| structure
210 this.points
= new Array(this.datasets
.length
);
212 // TODO(bhs): these loops are a hot-spot for high-point-count charts. In fact,
213 // on chrome+linux, they are 6 times more expensive than iterating through the
214 // points and drawing the lines. The brunt of the cost comes from allocating
215 // the |point| structures.
216 var boundaryIdStart
= this.dygraph_
.getLeftBoundary_();
217 for (var setIdx
= 0; setIdx
< this.datasets
.length
; setIdx
++) {
218 var dataset
= this.datasets
[setIdx
];
219 var setName
= this.setNames
[setIdx
];
220 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
221 // TODO (konigsberg): use optionsForAxis instead.
222 var logscale
= this.dygraph_
.attributes_
.getForSeries("logscale", setName
);
224 // Preallocating the size of points reduces reallocations, and therefore,
225 // calls to collect garbage.
226 var seriesPoints
= new Array(dataset
.length
);
228 for (var j
= 0; j
< dataset
.length
; j
++) {
229 var item
= dataset
[j
];
230 var xValue
= DygraphLayout
.parseFloat_(item
[0]);
231 var yValue
= DygraphLayout
.parseFloat_(item
[1]);
233 // Range from 0-1 where 0 represents left and 1 represents right.
234 var xNormal
= (xValue
- this.minxval
) * this.xscale
;
235 // Range from 0-1 where 0 represents top and 1 represents bottom
236 var yNormal
= DygraphLayout
._calcYNormal(axis
, yValue
, logscale
);
238 // TODO(danvk): drop the point in this case, don't null it.
239 // The nulls create complexity in DygraphCanvasRenderer._drawSeries.
240 if (connectSeparated
&& item
[1] === null) {
248 name
: setName
, // TODO(danvk): is this really necessary?
249 idx
: j
+ boundaryIdStart
253 this.points
[setIdx
] = seriesPoints
;
258 * Optimized replacement for parseFloat, which was way too slow when almost
259 * all values were type number, with few edge cases, none of which were strings.
261 DygraphLayout
.parseFloat_
= function(val
) {
262 // parseFloat(null) is NaN
267 // Assume it's a number or NaN. If it's something else, I'll be shocked.
271 DygraphLayout
.prototype._evaluateLineTicks
= function() {
272 var i
, tick
, label
, pos
;
274 for (i
= 0; i
< this.xTicks_
.length
; i
++) {
275 tick
= this.xTicks_
[i
];
277 pos
= this.xscale
* (tick
.v
- this.minxval
);
278 if ((pos
>= 0.0) && (pos
<= 1.0)) {
279 this.xticks
.push([pos
, label
]);
284 for (i
= 0; i
< this.yAxes_
.length
; i
++ ) {
285 var axis
= this.yAxes_
[i
];
286 for (var j
= 0; j
< axis
.ticks
.length
; j
++) {
287 tick
= axis
.ticks
[j
];
289 pos
= this.dygraph_
.toPercentYCoord(tick
.v
, i
);
290 if ((pos
>= 0.0) && (pos
<= 1.0)) {
291 this.yticks
.push([i
, pos
, label
]);
299 * Behaves the same way as PlotKit.Layout, but also copies the errors
302 DygraphLayout
.prototype.evaluateWithError
= function() {
304 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
306 // Copy over the error terms
307 var i
= 0; // index in this.points
308 for (var setIdx
= 0; setIdx
< this.datasets
.length
; ++setIdx
) {
309 var points
= this.points
[setIdx
];
311 var dataset
= this.datasets
[setIdx
];
312 var setName
= this.setNames
[setIdx
];
313 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
314 // TODO (konigsberg): use optionsForAxis instead.
315 var logscale
= this.dygraph_
.attributes_
.getForSeries("logscale", setName
);
317 for (j
= 0; j
< dataset
.length
; j
++, i
++) {
318 var item
= dataset
[j
];
319 var xv
= DygraphLayout
.parseFloat_(item
[0]);
320 var yv
= DygraphLayout
.parseFloat_(item
[1]);
322 if (xv
== points
[j
].xval
&&
323 yv
== points
[j
].yval
) {
324 var errorMinus
= DygraphLayout
.parseFloat_(item
[2]);
325 var errorPlus
= DygraphLayout
.parseFloat_(item
[3]);
327 var yv_minus
= yv
- errorMinus
;
328 var yv_plus
= yv
+ errorPlus
;
329 points
[j
].y_top
= DygraphLayout
._calcYNormal(axis
, yv_minus
, logscale
);
330 points
[j
].y_bottom
= DygraphLayout
._calcYNormal(axis
, yv_plus
, logscale
);
336 DygraphLayout
.prototype._evaluateAnnotations
= function() {
337 // Add the annotations to the point to which they belong.
338 // Make a map from (setName, xval) to annotation for quick lookups.
340 var annotations
= {};
341 for (i
= 0; i
< this.annotations
.length
; i
++) {
342 var a
= this.annotations
[i
];
343 annotations
[a
.xval
+ "," + a
.series
] = a
;
346 this.annotated_points
= [];
348 // Exit the function early if there are no annotations.
349 if (!this.annotations
|| !this.annotations
.length
) {
353 // TODO(antrob): loop through annotations not points.
354 for (var setIdx
= 0; setIdx
< this.points
.length
; setIdx
++) {
355 var points
= this.points
[setIdx
];
356 for (i
= 0; i
< points
.length
; i
++) {
358 var k
= p
.xval
+ "," + p
.name
;
359 if (k
in annotations
) {
360 p
.annotation
= annotations
[k
];
361 this.annotated_points
.push(p
);
368 * Convenience function to remove all the data sets from a graph
370 DygraphLayout
.prototype.removeAllDatasets
= function() {
371 delete this.datasets
;
372 delete this.setNames
;
373 delete this.setPointsLengths
;
374 delete this.setPointsOffsets
;
377 this.setPointsLengths
= [];
378 this.setPointsOffsets
= [];
382 * Return a copy of the point at the indicated index, with its yval unstacked.
383 * @param int index of point in layout_.points
385 DygraphLayout
.prototype.unstackPointAtIndex
= function(setIdx
, row
) {
386 var point
= this.points
[setIdx
][row
];
387 // If the point is missing, no unstacking is necessary
388 if (!Dygraph
.isValidPoint(point
)) {
392 // Clone the point since we modify it
393 var unstackedPoint
= {};
394 for (var pt
in point
) {
395 unstackedPoint
[pt
] = point
[pt
];
398 if (!this.attr_("stackedGraph")) {
399 return unstackedPoint
;
402 // The unstacked yval is equal to the current yval minus the yval of the
403 // next point at the same xval.
404 // We need to iterate over setIdx just in case some series have invalid values
406 for(setIdx
++; setIdx
< this.points
.length
; setIdx
++) {
407 var nextPoint
= this.points
[setIdx
][row
];
408 if (nextPoint
.xval
== point
.xval
&& // should always be true?
409 Dygraph
.isValidPoint(nextPoint
)) {
410 unstackedPoint
.yval
-= nextPoint
.yval
;
411 break; // stop at first valid point
415 return unstackedPoint
;