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
);
55 DygraphLayout
.prototype.getPlotArea
= function() {
56 return this.computePlotArea_();
59 // Compute the box which the chart should be drawn in. This is the canvas's
60 // box, less space needed for axis and chart labels.
61 DygraphLayout
.prototype.computePlotArea_
= function() {
63 // TODO(danvk): per-axis setting.
68 area
.w
= this.dygraph_
.width_
- area
.x
- this.attr_('rightGap');
69 area
.h
= this.dygraph_
.height_
;
71 // Let plugins reserve space.
73 chart_div
: this.dygraph_
.graphDiv
,
74 reserveSpaceLeft
: function(px
) {
85 reserveSpaceRight
: function(px
) {
87 x
: area
.x
+ area
.w
- px
,
95 reserveSpaceTop
: function(px
) {
106 reserveSpaceBottom
: function(px
) {
109 y
: area
.y
+ area
.h
- px
,
116 chartRect
: function() {
117 return {x
:area
.x
, y
:area
.y
, w
:area
.w
, h
:area
.h
};
120 this.dygraph_
.cascadeEvents_('layout', e
);
122 // Add space for range selector, if needed.
123 if (this.attr_('showRangeSelector')) {
124 area
.h
-= this.attr_('rangeSelectorHeight') + 4;
130 DygraphLayout
.prototype.setAnnotations
= function(ann
) {
131 // The Dygraph object's annotations aren't parsed. We parse them here and
132 // save a copy. If there is no parser, then the user must be using raw format.
133 this.annotations
= [];
134 var parse
= this.attr_('xValueParser') || function(x
) { return x
; };
135 for (var i
= 0; i
< ann
.length
; i
++) {
137 if (!ann
[i
].xval
&& !ann
[i
].x
) {
138 this.dygraph_
.error("Annotations must have an 'x' property");
142 !(ann
[i
].hasOwnProperty('width') &&
143 ann
[i
].hasOwnProperty('height'))) {
144 this.dygraph_
.error("Must set width and height when setting " +
145 "annotation.icon property");
148 Dygraph
.update(a
, ann
[i
]);
149 if (!a
.xval
) a
.xval
= parse(a
.x
);
150 this.annotations
.push(a
);
154 DygraphLayout
.prototype.setXTicks
= function(xTicks
) {
155 this.xTicks_
= xTicks
;
158 // TODO(danvk): add this to the Dygraph object's API or move it into Layout.
159 DygraphLayout
.prototype.setYAxes
= function (yAxes
) {
163 DygraphLayout
.prototype.setDateWindow
= function(dateWindow
) {
164 this.dateWindow_
= dateWindow
;
167 DygraphLayout
.prototype.evaluate
= function() {
168 this._evaluateLimits();
169 this._evaluateLineCharts();
170 this._evaluateLineTicks();
171 this._evaluateAnnotations();
174 DygraphLayout
.prototype._evaluateLimits
= function() {
175 this.minxval
= this.maxxval
= null;
176 if (this.dateWindow_
) {
177 this.minxval
= this.dateWindow_
[0];
178 this.maxxval
= this.dateWindow_
[1];
180 for (var setIdx
= 0; setIdx
< this.datasets
.length
; ++setIdx
) {
181 var series
= this.datasets
[setIdx
];
182 if (series
.length
> 1) {
183 var x1
= series
[0][0];
184 if (!this.minxval
|| x1
< this.minxval
) this.minxval
= x1
;
186 var x2
= series
[series
.length
- 1][0];
187 if (!this.maxxval
|| x2
> this.maxxval
) this.maxxval
= x2
;
191 this.xrange
= this.maxxval
- this.minxval
;
192 this.xscale
= (this.xrange
!== 0 ? 1/this.xrange
: 1.0);
194 for (var i
= 0; i
< this.yAxes_
.length
; i
++) {
195 var axis
= this.yAxes_
[i
];
196 axis
.minyval
= axis
.computedValueRange
[0];
197 axis
.maxyval
= axis
.computedValueRange
[1];
198 axis
.yrange
= axis
.maxyval
- axis
.minyval
;
199 axis
.yscale
= (axis
.yrange
!== 0 ? 1.0 / axis
.yrange
: 1.0);
201 if (axis
.g
.attr_("logscale")) {
202 axis
.ylogrange
= Dygraph
.log10(axis
.maxyval
) - Dygraph
.log10(axis
.minyval
);
203 axis
.ylogscale
= (axis
.ylogrange
!== 0 ? 1.0 / axis
.ylogrange
: 1.0);
204 if (!isFinite(axis
.ylogrange
) || isNaN(axis
.ylogrange
)) {
205 axis
.g
.error('axis ' + i
+ ' of graph at ' + axis
.g
+
206 ' can\'t be displayed in log scale for range [' +
207 axis
.minyval
+ ' - ' + axis
.maxyval
+ ']');
213 DygraphLayout
._calcYNormal
= function(axis
, value
) {
215 return 1.0 - ((Dygraph
.log10(value
) - Dygraph
.log10(axis
.minyval
)) * axis
.ylogscale
);
217 return 1.0 - ((value
- axis
.minyval
) * axis
.yscale
);
221 DygraphLayout
.prototype._evaluateLineCharts
= function() {
222 var connectSeparated
= this.attr_('connectSeparatedPoints');
224 // series index -> point index in series -> |point| structure
225 this.points
= new Array(this.datasets
.length
);
227 // TODO(bhs): these loops are a hot-spot for high-point-count charts. In fact,
228 // on chrome+linux, they are 6 times more expensive than iterating through the
229 // points and drawing the lines. The brunt of the cost comes from allocating
230 // the |point| structures.
231 for (var setIdx
= 0; setIdx
< this.datasets
.length
; setIdx
++) {
232 var dataset
= this.datasets
[setIdx
];
233 var setName
= this.setNames
[setIdx
];
234 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
236 // Preallocating the size of points reduces reallocations, and therefore,
237 // calls to collect garbage.
238 var seriesPoints
= new Array(dataset
.length
);
240 for (var j
= 0; j
< dataset
.length
; j
++) {
241 var item
= dataset
[j
];
242 var xValue
= DygraphLayout
.parseFloat_(item
[0]);
243 var yValue
= DygraphLayout
.parseFloat_(item
[1]);
245 // Range from 0-1 where 0 represents left and 1 represents right.
246 var xNormal
= (xValue
- this.minxval
) * this.xscale
;
247 // Range from 0-1 where 0 represents top and 1 represents bottom
248 var yNormal
= DygraphLayout
._calcYNormal(axis
, yValue
);
250 // TODO(danvk): drop the point in this case, don't null it.
251 // The nulls create complexity in DygraphCanvasRenderer._drawSeries.
252 if (connectSeparated
&& item
[1] === null) {
260 name
: setName
// TODO(danvk): is this really necessary?
264 this.points
[setIdx
] = seriesPoints
;
269 * Optimized replacement for parseFloat, which was way too slow when almost
270 * all values were type number, with few edge cases, none of which were strings.
272 DygraphLayout
.parseFloat_
= function(val
) {
273 // parseFloat(null) is NaN
278 // Assume it's a number or NaN. If it's something else, I'll be shocked.
282 DygraphLayout
.prototype._evaluateLineTicks
= function() {
283 var i
, tick
, label
, pos
;
285 for (i
= 0; i
< this.xTicks_
.length
; i
++) {
286 tick
= this.xTicks_
[i
];
288 pos
= this.xscale
* (tick
.v
- this.minxval
);
289 if ((pos
>= 0.0) && (pos
<= 1.0)) {
290 this.xticks
.push([pos
, label
]);
295 for (i
= 0; i
< this.yAxes_
.length
; i
++ ) {
296 var axis
= this.yAxes_
[i
];
297 for (var j
= 0; j
< axis
.ticks
.length
; j
++) {
298 tick
= axis
.ticks
[j
];
300 pos
= this.dygraph_
.toPercentYCoord(tick
.v
, i
);
301 if ((pos
>= 0.0) && (pos
<= 1.0)) {
302 this.yticks
.push([i
, pos
, label
]);
310 * Behaves the same way as PlotKit.Layout, but also copies the errors
313 DygraphLayout
.prototype.evaluateWithError
= function() {
315 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
317 // Copy over the error terms
318 var i
= 0; // index in this.points
319 for (var setIdx
= 0; setIdx
< this.datasets
.length
; ++setIdx
) {
320 var points
= this.points
[setIdx
];
322 var dataset
= this.datasets
[setIdx
];
323 var setName
= this.setNames
[setIdx
];
324 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
325 for (j
= 0; j
< dataset
.length
; j
++, i
++) {
326 var item
= dataset
[j
];
327 var xv
= DygraphLayout
.parseFloat_(item
[0]);
328 var yv
= DygraphLayout
.parseFloat_(item
[1]);
330 if (xv
== points
[j
].xval
&&
331 yv
== points
[j
].yval
) {
332 var errorMinus
= DygraphLayout
.parseFloat_(item
[2]);
333 var errorPlus
= DygraphLayout
.parseFloat_(item
[3]);
335 var yv_minus
= yv
- errorMinus
;
336 var yv_plus
= yv
+ errorPlus
;
337 points
[j
].y_top
= DygraphLayout
._calcYNormal(axis
, yv_minus
);
338 points
[j
].y_bottom
= DygraphLayout
._calcYNormal(axis
, yv_plus
);
344 DygraphLayout
.prototype._evaluateAnnotations
= function() {
345 // Add the annotations to the point to which they belong.
346 // Make a map from (setName, xval) to annotation for quick lookups.
348 var annotations
= {};
349 for (i
= 0; i
< this.annotations
.length
; i
++) {
350 var a
= this.annotations
[i
];
351 annotations
[a
.xval
+ "," + a
.series
] = a
;
354 this.annotated_points
= [];
356 // Exit the function early if there are no annotations.
357 if (!this.annotations
|| !this.annotations
.length
) {
361 // TODO(antrob): loop through annotations not points.
362 for (var setIdx
= 0; setIdx
< this.points
.length
; setIdx
++) {
363 var points
= this.points
[setIdx
];
364 for (i
= 0; i
< points
.length
; i
++) {
366 var k
= p
.xval
+ "," + p
.name
;
367 if (k
in annotations
) {
368 p
.annotation
= annotations
[k
];
369 this.annotated_points
.push(p
);
376 * Convenience function to remove all the data sets from a graph
378 DygraphLayout
.prototype.removeAllDatasets
= function() {
379 delete this.datasets
;
380 delete this.setNames
;
381 delete this.setPointsLengths
;
382 delete this.setPointsOffsets
;
385 this.setPointsLengths
= [];
386 this.setPointsOffsets
= [];
390 * Return a copy of the point at the indicated index, with its yval unstacked.
391 * @param int index of point in layout_.points
393 DygraphLayout
.prototype.unstackPointAtIndex
= function(setIdx
, row
) {
394 var point
= this.points
[setIdx
][row
];
395 // If the point is missing, no unstacking is necessary
400 // Clone the point since we modify it
401 var unstackedPoint
= {};
402 for (var pt
in point
) {
403 unstackedPoint
[pt
] = point
[pt
];
406 if (!this.attr_("stackedGraph")) {
407 return unstackedPoint
;
410 // The unstacked yval is equal to the current yval minus the yval of the
411 // next point at the same xval.
412 if (setIdx
== this.points
.length
- 1) {
413 // We're the last series, so no unstacking is necessary.
414 return unstackedPoint
;
417 var points
= this.points
[setIdx
+ 1];
418 if (points
[row
].xval
== point
.xval
&& // should always be true?
420 unstackedPoint
.yval
-= points
[row
].yval
;
423 return unstackedPoint
;