9e042f23f7ed8ba0c39073598eeb6f4067db9412
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() {
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 // NOTE: This should only be called by Dygraph.predraw_().
62 DygraphLayout
.prototype.computePlotArea
= function() {
64 // TODO(danvk): per-axis setting.
69 area
.w
= this.dygraph_
.width_
- area
.x
- this.attr_('rightGap');
70 area
.h
= this.dygraph_
.height_
;
72 // Let plugins reserve space.
74 chart_div
: this.dygraph_
.graphDiv
,
75 reserveSpaceLeft
: function(px
) {
86 reserveSpaceRight
: function(px
) {
88 x
: area
.x
+ area
.w
- px
,
96 reserveSpaceTop
: function(px
) {
107 reserveSpaceBottom
: function(px
) {
110 y
: area
.y
+ area
.h
- px
,
117 chartRect
: function() {
118 return {x
:area
.x
, y
:area
.y
, w
:area
.w
, h
:area
.h
};
121 this.dygraph_
.cascadeEvents_('layout', e
);
126 DygraphLayout
.prototype.setAnnotations
= function(ann
) {
127 // The Dygraph object's annotations aren't parsed. We parse them here and
128 // save a copy. If there is no parser, then the user must be using raw format.
129 this.annotations
= [];
130 var parse
= this.attr_('xValueParser') || function(x
) { return x
; };
131 for (var i
= 0; i
< ann
.length
; i
++) {
133 if (!ann
[i
].xval
&& ann
[i
].x
=== undefined
) {
134 this.dygraph_
.error("Annotations must have an 'x' property");
138 !(ann
[i
].hasOwnProperty('width') &&
139 ann
[i
].hasOwnProperty('height'))) {
140 this.dygraph_
.error("Must set width and height when setting " +
141 "annotation.icon property");
144 Dygraph
.update(a
, ann
[i
]);
145 if (!a
.xval
) a
.xval
= parse(a
.x
);
146 this.annotations
.push(a
);
150 DygraphLayout
.prototype.setXTicks
= function(xTicks
) {
151 this.xTicks_
= xTicks
;
154 // TODO(danvk): add this to the Dygraph object's API or move it into Layout.
155 DygraphLayout
.prototype.setYAxes
= function (yAxes
) {
159 DygraphLayout
.prototype.setDateWindow
= function(dateWindow
) {
160 this.dateWindow_
= dateWindow
;
163 DygraphLayout
.prototype.evaluate
= function() {
164 this._evaluateLimits();
165 this._evaluateLineCharts();
166 this._evaluateLineTicks();
167 this._evaluateAnnotations();
170 DygraphLayout
.prototype._evaluateLimits
= function() {
171 var xlimits
= this.dygraph_
.xAxisRange();
172 this.minxval
= xlimits
[0];
173 this.maxxval
= xlimits
[1];
174 var xrange
= xlimits
[1] - xlimits
[0];
175 this.xscale
= (xrange
!== 0 ? 1 / xrange
: 1.0);
177 for (var i
= 0; i
< this.yAxes_
.length
; i
++) {
178 var axis
= this.yAxes_
[i
];
179 axis
.minyval
= axis
.computedValueRange
[0];
180 axis
.maxyval
= axis
.computedValueRange
[1];
181 axis
.yrange
= axis
.maxyval
- axis
.minyval
;
182 axis
.yscale
= (axis
.yrange
!== 0 ? 1.0 / axis
.yrange
: 1.0);
184 if (axis
.g
.attr_("logscale")) {
185 axis
.ylogrange
= Dygraph
.log10(axis
.maxyval
) - Dygraph
.log10(axis
.minyval
);
186 axis
.ylogscale
= (axis
.ylogrange
!== 0 ? 1.0 / axis
.ylogrange
: 1.0);
187 if (!isFinite(axis
.ylogrange
) || isNaN(axis
.ylogrange
)) {
188 axis
.g
.error('axis ' + i
+ ' of graph at ' + axis
.g
+
189 ' can\'t be displayed in log scale for range [' +
190 axis
.minyval
+ ' - ' + axis
.maxyval
+ ']');
196 DygraphLayout
._calcYNormal
= function(axis
, value
, logscale
) {
198 return 1.0 - ((Dygraph
.log10(value
) - Dygraph
.log10(axis
.minyval
)) * axis
.ylogscale
);
200 return 1.0 - ((value
- axis
.minyval
) * axis
.yscale
);
204 DygraphLayout
.prototype._evaluateLineCharts
= function() {
205 var connectSeparated
= this.attr_('connectSeparatedPoints');
207 // series index -> point index in series -> |point| structure
208 this.points
= new Array(this.datasets
.length
);
210 // TODO(bhs): these loops are a hot-spot for high-point-count charts. In fact,
211 // on chrome+linux, they are 6 times more expensive than iterating through the
212 // points and drawing the lines. The brunt of the cost comes from allocating
213 // the |point| structures.
214 var boundaryIdStart
= this.dygraph_
.getLeftBoundary_();
215 for (var setIdx
= 0; setIdx
< this.datasets
.length
; setIdx
++) {
216 var dataset
= this.datasets
[setIdx
];
217 var setName
= this.setNames
[setIdx
];
218 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
219 // TODO (konigsberg): use optionsForAxis instead.
220 var logscale
= this.dygraph_
.attributes_
.getForSeries("logscale", setName
);
222 // Preallocating the size of points reduces reallocations, and therefore,
223 // calls to collect garbage.
224 var seriesPoints
= new Array(dataset
.length
);
226 for (var j
= 0; j
< dataset
.length
; j
++) {
227 var item
= dataset
[j
];
228 var xValue
= DygraphLayout
.parseFloat_(item
[0]);
229 var yValue
= DygraphLayout
.parseFloat_(item
[1]);
231 // Range from 0-1 where 0 represents left and 1 represents right.
232 var xNormal
= (xValue
- this.minxval
) * this.xscale
;
233 // Range from 0-1 where 0 represents top and 1 represents bottom
234 var yNormal
= DygraphLayout
._calcYNormal(axis
, yValue
, logscale
);
236 // TODO(danvk): drop the point in this case, don't null it.
237 // The nulls create complexity in DygraphCanvasRenderer._drawSeries.
238 if (connectSeparated
&& item
[1] === null) {
246 name
: setName
, // TODO(danvk): is this really necessary?
247 idx
: j
+ boundaryIdStart
251 this.points
[setIdx
] = seriesPoints
;
256 * Optimized replacement for parseFloat, which was way too slow when almost
257 * all values were type number, with few edge cases, none of which were strings.
259 DygraphLayout
.parseFloat_
= function(val
) {
260 // parseFloat(null) is NaN
265 // Assume it's a number or NaN. If it's something else, I'll be shocked.
269 DygraphLayout
.prototype._evaluateLineTicks
= function() {
270 var i
, tick
, label
, pos
;
272 for (i
= 0; i
< this.xTicks_
.length
; i
++) {
273 tick
= this.xTicks_
[i
];
275 pos
= this.xscale
* (tick
.v
- this.minxval
);
276 if ((pos
>= 0.0) && (pos
<= 1.0)) {
277 this.xticks
.push([pos
, label
]);
282 for (i
= 0; i
< this.yAxes_
.length
; i
++ ) {
283 var axis
= this.yAxes_
[i
];
284 for (var j
= 0; j
< axis
.ticks
.length
; j
++) {
285 tick
= axis
.ticks
[j
];
287 pos
= this.dygraph_
.toPercentYCoord(tick
.v
, i
);
288 if ((pos
>= 0.0) && (pos
<= 1.0)) {
289 this.yticks
.push([i
, pos
, label
]);
297 * Behaves the same way as PlotKit.Layout, but also copies the errors
300 DygraphLayout
.prototype.evaluateWithError
= function() {
302 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
304 // Copy over the error terms
305 var i
= 0; // index in this.points
306 for (var setIdx
= 0; setIdx
< this.datasets
.length
; ++setIdx
) {
307 var points
= this.points
[setIdx
];
309 var dataset
= this.datasets
[setIdx
];
310 var setName
= this.setNames
[setIdx
];
311 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
312 // TODO (konigsberg): use optionsForAxis instead.
313 var logscale
= this.dygraph_
.attributes_
.getForSeries("logscale", setName
);
315 for (j
= 0; j
< dataset
.length
; j
++, i
++) {
316 var item
= dataset
[j
];
317 var xv
= DygraphLayout
.parseFloat_(item
[0]);
318 var yv
= DygraphLayout
.parseFloat_(item
[1]);
320 if (xv
== points
[j
].xval
&&
321 yv
== points
[j
].yval
) {
322 var errorMinus
= DygraphLayout
.parseFloat_(item
[2]);
323 var errorPlus
= DygraphLayout
.parseFloat_(item
[3]);
325 var yv_minus
= yv
- errorMinus
;
326 var yv_plus
= yv
+ errorPlus
;
327 points
[j
].y_top
= DygraphLayout
._calcYNormal(axis
, yv_minus
, logscale
);
328 points
[j
].y_bottom
= DygraphLayout
._calcYNormal(axis
, yv_plus
, logscale
);
334 DygraphLayout
.prototype._evaluateAnnotations
= function() {
335 // Add the annotations to the point to which they belong.
336 // Make a map from (setName, xval) to annotation for quick lookups.
338 var annotations
= {};
339 for (i
= 0; i
< this.annotations
.length
; i
++) {
340 var a
= this.annotations
[i
];
341 annotations
[a
.xval
+ "," + a
.series
] = a
;
344 this.annotated_points
= [];
346 // Exit the function early if there are no annotations.
347 if (!this.annotations
|| !this.annotations
.length
) {
351 // TODO(antrob): loop through annotations not points.
352 for (var setIdx
= 0; setIdx
< this.points
.length
; setIdx
++) {
353 var points
= this.points
[setIdx
];
354 for (i
= 0; i
< points
.length
; i
++) {
356 var k
= p
.xval
+ "," + p
.name
;
357 if (k
in annotations
) {
358 p
.annotation
= annotations
[k
];
359 this.annotated_points
.push(p
);
366 * Convenience function to remove all the data sets from a graph
368 DygraphLayout
.prototype.removeAllDatasets
= function() {
369 delete this.datasets
;
370 delete this.setNames
;
371 delete this.setPointsLengths
;
372 delete this.setPointsOffsets
;
375 this.setPointsLengths
= [];
376 this.setPointsOffsets
= [];
380 * Return a copy of the point at the indicated index, with its yval unstacked.
381 * @param int index of point in layout_.points
383 DygraphLayout
.prototype.unstackPointAtIndex
= function(setIdx
, row
) {
384 var point
= this.points
[setIdx
][row
];
385 // If the point is missing, no unstacking is necessary
386 if (!Dygraph
.isValidPoint(point
)) {
390 // Clone the point since we modify it
391 var unstackedPoint
= {};
392 for (var pt
in point
) {
393 unstackedPoint
[pt
] = point
[pt
];
396 if (!this.attr_("stackedGraph")) {
397 return unstackedPoint
;
400 // The unstacked yval is equal to the current yval minus the yval of the
401 // next point at the same xval.
402 // We need to iterate over setIdx just in case some series have invalid values
404 for(setIdx
++; setIdx
< this.points
.length
; setIdx
++) {
405 var nextPoint
= this.points
[setIdx
][row
];
406 if (nextPoint
.xval
== point
.xval
&& // should always be true?
407 Dygraph
.isValidPoint(nextPoint
)) {
408 unstackedPoint
.yval
-= nextPoint
.yval
;
409 break; // stop at first valid point
413 return unstackedPoint
;