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
;
35 this.annotations
= [];
38 // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
39 // yticks are outputs. Clean this up.
44 DygraphLayout
.prototype.attr_
= function(name
) {
45 return this.dygraph_
.attr_(name
);
48 DygraphLayout
.prototype.addDataset
= function(setname
, set_xy
) {
49 this.datasets
[setname
] = set_xy
;
52 DygraphLayout
.prototype.getPlotArea
= function() {
53 return this.computePlotArea_();
56 // Compute the box which the chart should be drawn in. This is the canvas's
57 // box, less space needed for axis and chart labels.
58 DygraphLayout
.prototype.computePlotArea_
= function() {
60 // TODO(danvk): per-axis setting.
64 if (this.attr_('drawYAxis')) {
65 area
.x
= this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize');
68 area
.w
= this.dygraph_
.width_
- area
.x
- this.attr_('rightGap');
69 area
.h
= this.dygraph_
.height_
;
70 if (this.attr_('drawXAxis')) {
71 if (this.attr_('xAxisHeight')) {
72 area
.h
-= this.attr_('xAxisHeight');
74 area
.h
-= this.attr_('axisLabelFontSize') + 2 * this.attr_('axisTickSize');
78 // Shrink the drawing area to accomodate additional y-axes.
79 if (this.dygraph_
.numAxes() == 2) {
80 // TODO(danvk): per-axis setting.
81 area
.w
-= (this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize'));
82 } else if (this.dygraph_
.numAxes() > 2) {
83 this.dygraph_
.error("Only two y-axes are supported at this time. (Trying " +
84 "to use " + this.dygraph_
.numAxes() + ")");
87 // Add space for chart labels: title, xlabel and ylabel.
88 if (this.attr_('title')) {
89 area
.h
-= this.attr_('titleHeight');
90 area
.y
+= this.attr_('titleHeight');
92 if (this.attr_('xlabel')) {
93 area
.h
-= this.attr_('xLabelHeight');
95 if (this.attr_('ylabel')) {
96 // It would make sense to shift the chart here to make room for the y-axis
97 // label, but the default yAxisLabelWidth is large enough that this results
98 // in overly-padded charts. The y-axis label should fit fine. If it
99 // doesn't, the yAxisLabelWidth option can be increased.
102 if (this.attr_('y2label')) {
103 // same logic applies here as for ylabel.
104 // TODO(danvk): make yAxisLabelWidth a per-axis property
107 // Add space for range selector, if needed.
108 if (this.attr_('showRangeSelector')) {
109 area
.h
-= this.attr_('rangeSelectorHeight') + 4;
115 DygraphLayout
.prototype.setAnnotations
= function(ann
) {
116 // The Dygraph object's annotations aren't parsed. We parse them here and
117 // save a copy. If there is no parser, then the user must be using raw format.
118 this.annotations
= [];
119 var parse
= this.attr_('xValueParser') || function(x
) { return x
; };
120 for (var i
= 0; i
< ann
.length
; i
++) {
122 if (!ann
[i
].xval
&& !ann
[i
].x
) {
123 this.dygraph_
.error("Annotations must have an 'x' property");
127 !(ann
[i
].hasOwnProperty('width') &&
128 ann
[i
].hasOwnProperty('height'))) {
129 this.dygraph_
.error("Must set width and height when setting " +
130 "annotation.icon property");
133 Dygraph
.update(a
, ann
[i
]);
134 if (!a
.xval
) a
.xval
= parse(a
.x
);
135 this.annotations
.push(a
);
139 DygraphLayout
.prototype.setXTicks
= function(xTicks
) {
140 this.xTicks_
= xTicks
;
143 // TODO(danvk): add this to the Dygraph object's API or move it into Layout.
144 DygraphLayout
.prototype.setYAxes
= function (yAxes
) {
148 DygraphLayout
.prototype.setDateWindow
= function(dateWindow
) {
149 this.dateWindow_
= dateWindow
;
152 DygraphLayout
.prototype.evaluate
= function() {
153 this._evaluateLimits();
154 this._evaluateLineCharts();
155 this._evaluateLineTicks();
156 this._evaluateAnnotations();
159 DygraphLayout
.prototype._evaluateLimits
= function() {
160 this.minxval
= this.maxxval
= null;
161 if (this.dateWindow_
) {
162 this.minxval
= this.dateWindow_
[0];
163 this.maxxval
= this.dateWindow_
[1];
165 for (var name
in this.datasets
) {
166 if (!this.datasets
.hasOwnProperty(name
)) continue;
167 var series
= this.datasets
[name
];
168 if (series
.length
> 1) {
169 var x1
= series
[0][0];
170 if (!this.minxval
|| x1
< this.minxval
) this.minxval
= x1
;
172 var x2
= series
[series
.length
- 1][0];
173 if (!this.maxxval
|| x2
> this.maxxval
) this.maxxval
= x2
;
177 this.xrange
= this.maxxval
- this.minxval
;
178 this.xscale
= (this.xrange
!== 0 ? 1/this.xrange
: 1.0);
180 for (var i
= 0; i
< this.yAxes_
.length
; i
++) {
181 var axis
= this.yAxes_
[i
];
182 axis
.minyval
= axis
.computedValueRange
[0];
183 axis
.maxyval
= axis
.computedValueRange
[1];
184 axis
.yrange
= axis
.maxyval
- axis
.minyval
;
185 axis
.yscale
= (axis
.yrange
!== 0 ? 1.0 / axis
.yrange
: 1.0);
187 if (axis
.g
.attr_("logscale")) {
188 axis
.ylogrange
= Dygraph
.log10(axis
.maxyval
) - Dygraph
.log10(axis
.minyval
);
189 axis
.ylogscale
= (axis
.ylogrange
!== 0 ? 1.0 / axis
.ylogrange
: 1.0);
190 if (!isFinite(axis
.ylogrange
) || isNaN(axis
.ylogrange
)) {
191 axis
.g
.error('axis ' + i
+ ' of graph at ' + axis
.g
+
192 ' can\'t be displayed in log scale for range [' +
193 axis
.minyval
+ ' - ' + axis
.maxyval
+ ']');
199 DygraphLayout
._calcYNormal
= function(axis
, value
) {
201 return 1.0 - ((Dygraph
.log10(value
) - Dygraph
.log10(axis
.minyval
)) * axis
.ylogscale
);
203 return 1.0 - ((value
- axis
.minyval
) * axis
.yscale
);
207 DygraphLayout
.prototype._evaluateLineCharts
= function() {
210 // An array to keep track of how many points will be drawn for each set.
211 // This will allow for the canvas renderer to not have to check every point
212 // for every data set since the points are added in order of the sets in
214 this.setPointsLengths
= [];
216 for (var setName
in this.datasets
) {
217 if (!this.datasets
.hasOwnProperty(setName
)) continue;
219 var dataset
= this.datasets
[setName
];
220 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
222 var setPointsLength
= 0;
224 for (var j
= 0; j
< dataset
.length
; j
++) {
225 var item
= dataset
[j
];
226 var xValue
= parseFloat(item
[0]);
227 var yValue
= parseFloat(item
[1]);
229 // Range from 0-1 where 0 represents left and 1 represents right.
230 var xNormal
= (xValue
- this.minxval
) * this.xscale
;
231 // Range from 0-1 where 0 represents top and 1 represents bottom
232 var yNormal
= DygraphLayout
._calcYNormal(axis
, yValue
);
242 this.points
.push(point
);
243 setPointsLength
+= 1;
245 this.setPointsLengths
.push(setPointsLength
);
249 DygraphLayout
.prototype._evaluateLineTicks
= function() {
250 var i
, tick
, label
, pos
;
252 for (i
= 0; i
< this.xTicks_
.length
; i
++) {
253 tick
= this.xTicks_
[i
];
255 pos
= this.xscale
* (tick
.v
- this.minxval
);
256 if ((pos
>= 0.0) && (pos
<= 1.0)) {
257 this.xticks
.push([pos
, label
]);
262 for (i
= 0; i
< this.yAxes_
.length
; i
++ ) {
263 var axis
= this.yAxes_
[i
];
264 for (var j
= 0; j
< axis
.ticks
.length
; j
++) {
265 tick
= axis
.ticks
[j
];
267 pos
= this.dygraph_
.toPercentYCoord(tick
.v
, i
);
268 if ((pos
>= 0.0) && (pos
<= 1.0)) {
269 this.yticks
.push([i
, pos
, label
]);
277 * Behaves the same way as PlotKit.Layout, but also copies the errors
280 DygraphLayout
.prototype.evaluateWithError
= function() {
282 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
284 // Copy over the error terms
285 var i
= 0; // index in this.points
286 for (var setName
in this.datasets
) {
287 if (!this.datasets
.hasOwnProperty(setName
)) continue;
289 var dataset
= this.datasets
[setName
];
290 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
291 for (j
= 0; j
< dataset
.length
; j
++, i
++) {
292 var item
= dataset
[j
];
293 var xv
= parseFloat(item
[0]);
294 var yv
= parseFloat(item
[1]);
296 if (xv
== this.points
[i
].xval
&&
297 yv
== this.points
[i
].yval
) {
298 var errorMinus
= parseFloat(item
[2]);
299 var errorPlus
= parseFloat(item
[3]);
301 var yv_minus
= yv
- errorMinus
;
302 var yv_plus
= yv
+ errorPlus
;
303 this.points
[i
].y_top
= DygraphLayout
._calcYNormal(axis
, yv_minus
);
304 this.points
[i
].y_bottom
= DygraphLayout
._calcYNormal(axis
, yv_plus
);
310 DygraphLayout
.prototype._evaluateAnnotations
= function() {
311 // Add the annotations to the point to which they belong.
312 // Make a map from (setName, xval) to annotation for quick lookups.
314 var annotations
= {};
315 for (i
= 0; i
< this.annotations
.length
; i
++) {
316 var a
= this.annotations
[i
];
317 annotations
[a
.xval
+ "," + a
.series
] = a
;
320 this.annotated_points
= [];
322 // Exit the function early if there are no annotations.
323 if (!this.annotations
|| !this.annotations
.length
) {
327 // TODO(antrob): loop through annotations not points.
328 for (i
= 0; i
< this.points
.length
; i
++) {
329 var p
= this.points
[i
];
330 var k
= p
.xval
+ "," + p
.name
;
331 if (k
in annotations
) {
332 p
.annotation
= annotations
[k
];
333 this.annotated_points
.push(p
);
339 * Convenience function to remove all the data sets from a graph
341 DygraphLayout
.prototype.removeAllDatasets
= function() {
342 delete this.datasets
;
347 * Return a copy of the point at the indicated index, with its yval unstacked.
348 * @param int index of point in layout_.points
350 DygraphLayout
.prototype.unstackPointAtIndex
= function(idx
) {
351 var point
= this.points
[idx
];
353 // Clone the point since we modify it
354 var unstackedPoint
= {};
355 for (var pt
in point
) {
356 unstackedPoint
[pt
] = point
[pt
];
359 if (!this.attr_("stackedGraph")) {
360 return unstackedPoint
;
363 // The unstacked yval is equal to the current yval minus the yval of the
364 // next point at the same xval.
365 for (var i
= idx
+1; i
< this.points
.length
; i
++) {
366 if (this.points
[i
].xval
== point
.xval
) {
367 unstackedPoint
.yval
-= this.points
[i
].yval
;
372 return unstackedPoint
;