Extract the granularity-picking code of the date ticker into a new function.
[dygraphs.git] / dygraph-tickers.js
1 /**
2 * @license
3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
8 * @fileoverview Description of this file.
9 * @author danvk@google.com (Dan Vanderkam)
10 *
11 * A ticker is a function with the following interface:
12 *
13 * function(a, b, pixels, options_view, dygraph, forced_values);
14 * -> [ { v: tick1_v, label: tick1_label[, label_v: label_v1] },
15 * { v: tick2_v, label: tick2_label[, label_v: label_v2] },
16 * ...
17 * ]
18 *
19 * The returned value is called a "tick list".
20 *
21 * Arguments
22 * ---------
23 *
24 * [a, b] is the range of the axis for which ticks are being generated. For a
25 * numeric axis, these will simply be numbers. For a date axis, these will be
26 * millis since epoch (convertable to Date objects using "new Date(a)" and "new
27 * Date(b)").
28 *
29 * opts provides access to chart- and axis-specific options. It can be used to
30 * access number/date formatting code/options, check for a log scale, etc.
31 *
32 * pixels is the length of the axis in pixels. opts('pixelsPerLabel') is the
33 * minimum amount of space to be allotted to each label. For instance, if
34 * pixels=400 and opts('pixelsPerLabel')=40 then the ticker should return
35 * between zero and ten (400/40) ticks.
36 *
37 * dygraph is the Dygraph object for which an axis is being constructed.
38 *
39 * forced_values is used for secondary y-axes. The tick positions are typically
40 * set by the primary y-axis, so the secondary y-axis has no choice in where to
41 * put these. It simply has to generate labels for these data values.
42 *
43 * Tick lists
44 * ----------
45 * Typically a tick will have both a grid/tick line and a label at one end of
46 * that line (at the bottom for an x-axis, at left or right for the y-axis).
47 *
48 * A tick may be missing one of these two components:
49 * - If "label_v" is specified instead of "v", then there will be no tick or
50 * gridline, just a label.
51 * - Similarly, if "label" is not specified, then there will be a gridline
52 * without a label.
53 *
54 * This flexibility is useful in a few situations:
55 * - For log scales, some of the tick lines may be too close to all have labels.
56 * - For date scales where years are being displayed, it is desirable to display
57 * tick marks at the beginnings of years but labels (e.g. "2006") in the
58 * middle of the years.
59 */
60
61 /*jshint globalstrict: true */
62 /*global Dygraph:false */
63 "use strict";
64
65 Dygraph.numericTicks = function(a, b, pixels, opts, dygraph, vals) {
66 var pixels_per_tick = opts('pixelsPerLabel');
67 var ticks = [];
68 var i, j, tickV, nTicks;
69 if (vals) {
70 for (i = 0; i < vals.length; i++) {
71 ticks.push({v: vals[i]});
72 }
73 } else {
74 // TODO(danvk): factor this log-scale block out into a separate function.
75 if (opts("logscale")) {
76 nTicks = Math.floor(pixels / pixels_per_tick);
77 var minIdx = Dygraph.binarySearch(a, Dygraph.PREFERRED_LOG_TICK_VALUES, 1);
78 var maxIdx = Dygraph.binarySearch(b, Dygraph.PREFERRED_LOG_TICK_VALUES, -1);
79 if (minIdx == -1) {
80 minIdx = 0;
81 }
82 if (maxIdx == -1) {
83 maxIdx = Dygraph.PREFERRED_LOG_TICK_VALUES.length - 1;
84 }
85 // Count the number of tick values would appear, if we can get at least
86 // nTicks / 4 accept them.
87 var lastDisplayed = null;
88 if (maxIdx - minIdx >= nTicks / 4) {
89 for (var idx = maxIdx; idx >= minIdx; idx--) {
90 var tickValue = Dygraph.PREFERRED_LOG_TICK_VALUES[idx];
91 var pixel_coord = Math.log(tickValue / a) / Math.log(b / a) * pixels;
92 var tick = { v: tickValue };
93 if (lastDisplayed === null) {
94 lastDisplayed = {
95 tickValue : tickValue,
96 pixel_coord : pixel_coord
97 };
98 } else {
99 if (Math.abs(pixel_coord - lastDisplayed.pixel_coord) >= pixels_per_tick) {
100 lastDisplayed = {
101 tickValue : tickValue,
102 pixel_coord : pixel_coord
103 };
104 } else {
105 tick.label = "";
106 }
107 }
108 ticks.push(tick);
109 }
110 // Since we went in backwards order.
111 ticks.reverse();
112 }
113 }
114
115 // ticks.length won't be 0 if the log scale function finds values to insert.
116 if (ticks.length === 0) {
117 // Basic idea:
118 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
119 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks).
120 // The first spacing greater than pixelsPerYLabel is what we use.
121 // TODO(danvk): version that works on a log scale.
122 var kmg2 = opts("labelsKMG2");
123 var mults;
124 if (kmg2) {
125 mults = [1, 2, 4, 8];
126 } else {
127 mults = [1, 2, 5];
128 }
129 var scale, low_val, high_val;
130 for (i = -10; i < 50; i++) {
131 var base_scale;
132 if (kmg2) {
133 base_scale = Math.pow(16, i);
134 } else {
135 base_scale = Math.pow(10, i);
136 }
137 var spacing = 0;
138 for (j = 0; j < mults.length; j++) {
139 scale = base_scale * mults[j];
140 low_val = Math.floor(a / scale) * scale;
141 high_val = Math.ceil(b / scale) * scale;
142 nTicks = Math.abs(high_val - low_val) / scale;
143 spacing = pixels / nTicks;
144 // wish I could break out of both loops at once...
145 if (spacing > pixels_per_tick) break;
146 }
147 if (spacing > pixels_per_tick) break;
148 }
149
150 // Construct the set of ticks.
151 // Allow reverse y-axis if it's explicitly requested.
152 if (low_val > high_val) scale *= -1;
153 for (i = 0; i < nTicks; i++) {
154 tickV = low_val + i * scale;
155 ticks.push( {v: tickV} );
156 }
157 }
158 }
159
160 // Add formatted labels to the ticks.
161 var k;
162 var k_labels = [];
163 if (opts("labelsKMB")) {
164 k = 1000;
165 k_labels = [ "K", "M", "B", "T" ];
166 }
167 if (opts("labelsKMG2")) {
168 if (k) Dygraph.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
169 k = 1024;
170 k_labels = [ "k", "M", "G", "T" ];
171 }
172
173 var formatter = opts('axisLabelFormatter');
174
175 // Add labels to the ticks.
176 for (i = 0; i < ticks.length; i++) {
177 if (ticks[i].label !== undefined) continue; // Use current label.
178 tickV = ticks[i].v;
179 var absTickV = Math.abs(tickV);
180 // TODO(danvk): set granularity to something appropriate here.
181 var label = formatter(tickV, 0, opts, dygraph);
182 if (k_labels.length > 0) {
183 // TODO(danvk): should this be integrated into the axisLabelFormatter?
184 // Round up to an appropriate unit.
185 var n = k*k*k*k;
186 for (j = 3; j >= 0; j--, n /= k) {
187 if (absTickV >= n) {
188 label = Dygraph.round_(tickV / n, opts('digitsAfterDecimal')) +
189 k_labels[j];
190 break;
191 }
192 }
193 }
194 ticks[i].label = label;
195 }
196
197 return ticks;
198 };
199
200
201 Dygraph.dateTicker = function(a, b, pixels, opts, dygraph, vals) {
202 var chosen = Dygraph.pickDateTickGranularity(a, b, pixels, opts);
203
204 if (chosen >= 0) {
205 return Dygraph.getDateAxis(a, b, chosen, opts, dygraph);
206 } else {
207 // this can happen if self.width_ is zero.
208 return [];
209 }
210 };
211
212 // Time granularity enumeration
213 Dygraph.SECONDLY = 0;
214 Dygraph.TWO_SECONDLY = 1;
215 Dygraph.FIVE_SECONDLY = 2;
216 Dygraph.TEN_SECONDLY = 3;
217 Dygraph.THIRTY_SECONDLY = 4;
218 Dygraph.MINUTELY = 5;
219 Dygraph.TWO_MINUTELY = 6;
220 Dygraph.FIVE_MINUTELY = 7;
221 Dygraph.TEN_MINUTELY = 8;
222 Dygraph.THIRTY_MINUTELY = 9;
223 Dygraph.HOURLY = 10;
224 Dygraph.TWO_HOURLY = 11;
225 Dygraph.SIX_HOURLY = 12;
226 Dygraph.DAILY = 13;
227 Dygraph.WEEKLY = 14;
228 Dygraph.MONTHLY = 15;
229 Dygraph.QUARTERLY = 16;
230 Dygraph.BIANNUAL = 17;
231 Dygraph.ANNUAL = 18;
232 Dygraph.DECADAL = 19;
233 Dygraph.CENTENNIAL = 20;
234 Dygraph.NUM_GRANULARITIES = 21;
235
236 Dygraph.SHORT_SPACINGS = [];
237 Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY] = 1000 * 1;
238 Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY] = 1000 * 2;
239 Dygraph.SHORT_SPACINGS[Dygraph.FIVE_SECONDLY] = 1000 * 5;
240 Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY] = 1000 * 10;
241 Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY] = 1000 * 30;
242 Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY] = 1000 * 60;
243 Dygraph.SHORT_SPACINGS[Dygraph.TWO_MINUTELY] = 1000 * 60 * 2;
244 Dygraph.SHORT_SPACINGS[Dygraph.FIVE_MINUTELY] = 1000 * 60 * 5;
245 Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY] = 1000 * 60 * 10;
246 Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY] = 1000 * 60 * 30;
247 Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600;
248 Dygraph.SHORT_SPACINGS[Dygraph.TWO_HOURLY] = 1000 * 3600 * 2;
249 Dygraph.SHORT_SPACINGS[Dygraph.SIX_HOURLY] = 1000 * 3600 * 6;
250 Dygraph.SHORT_SPACINGS[Dygraph.DAILY] = 1000 * 86400;
251 Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY] = 1000 * 604800;
252
253 /**
254 * @private
255 * This is a list of human-friendly values at which to show tick marks on a log
256 * scale. It is k * 10^n, where k=1..9 and n=-39..+39, so:
257 * ..., 1, 2, 3, 4, 5, ..., 9, 10, 20, 30, ..., 90, 100, 200, 300, ...
258 * NOTE: this assumes that Dygraph.LOG_SCALE = 10.
259 */
260 Dygraph.PREFERRED_LOG_TICK_VALUES = function() {
261 var vals = [];
262 for (var power = -39; power <= 39; power++) {
263 var range = Math.pow(10, power);
264 for (var mult = 1; mult <= 9; mult++) {
265 var val = range * mult;
266 vals.push(val);
267 }
268 }
269 return vals;
270 }();
271
272 /**
273 * Determine the correct granularity of ticks on a date axis.
274 *
275 * @param {Number} a Left edge of the chart (ms)
276 * @param {Number} b Right edge of the chart (ms)
277 * @param {Number} pixels Size of the chart in the relevant dimension (width).
278 * @param {Function} opts Function mapping from option name -> value.
279 * @return {Number} The appropriate axis granularity for this chart. See the
280 * enumeration of possible values in dygraph-tickers.js.
281 */
282 Dygraph.pickDateTickGranularity = function(a, b, pixels, opts) {
283 var pixels_per_tick = opts('pixelsPerLabel');
284 for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) {
285 var num_ticks = Dygraph.numDateTicks(a, b, i);
286 if (pixels / num_ticks >= pixels_per_tick) {
287 return i;
288 }
289 }
290 return -1;
291 };
292
293 Dygraph.numDateTicks = function(start_time, end_time, granularity) {
294 if (granularity < Dygraph.MONTHLY) {
295 // Generate one tick mark for every fixed interval of time.
296 var spacing = Dygraph.SHORT_SPACINGS[granularity];
297 return Math.floor(0.5 + 1.0 * (end_time - start_time) / spacing);
298 } else {
299 var year_mod = 1; // e.g. to only print one point every 10 years.
300 var num_months = 12;
301 if (granularity == Dygraph.QUARTERLY) num_months = 3;
302 if (granularity == Dygraph.BIANNUAL) num_months = 2;
303 if (granularity == Dygraph.ANNUAL) num_months = 1;
304 if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; }
305 if (granularity == Dygraph.CENTENNIAL) { num_months = 1; year_mod = 100; }
306
307 var msInYear = 365.2524 * 24 * 3600 * 1000;
308 var num_years = 1.0 * (end_time - start_time) / msInYear;
309 return Math.floor(0.5 + 1.0 * num_years * num_months / year_mod);
310 }
311 };
312
313 Dygraph.getDateAxis = function(start_time, end_time, granularity, opts, dg) {
314 var formatter = opts("axisLabelFormatter");
315 var ticks = [];
316 var t;
317
318 if (granularity < Dygraph.MONTHLY) {
319 // Generate one tick mark for every fixed interval of time.
320 var spacing = Dygraph.SHORT_SPACINGS[granularity];
321
322 // Find a time less than start_time which occurs on a "nice" time boundary
323 // for this granularity.
324 var g = spacing / 1000;
325 var d = new Date(start_time);
326 var x;
327 if (g <= 60) { // seconds
328 x = d.getSeconds(); d.setSeconds(x - x % g);
329 } else {
330 d.setSeconds(0);
331 g /= 60;
332 if (g <= 60) { // minutes
333 x = d.getMinutes(); d.setMinutes(x - x % g);
334 } else {
335 d.setMinutes(0);
336 g /= 60;
337
338 if (g <= 24) { // days
339 x = d.getHours(); d.setHours(x - x % g);
340 } else {
341 d.setHours(0);
342 g /= 24;
343
344 if (g == 7) { // one week
345 d.setDate(d.getDate() - d.getDay());
346 }
347 }
348 }
349 }
350 start_time = d.getTime();
351
352 for (t = start_time; t <= end_time; t += spacing) {
353 ticks.push({ v:t,
354 label: formatter(new Date(t), granularity, opts, dg)
355 });
356 }
357 } else {
358 // Display a tick mark on the first of a set of months of each year.
359 // Years get a tick mark iff y % year_mod == 0. This is useful for
360 // displaying a tick mark once every 10 years, say, on long time scales.
361 var months;
362 var year_mod = 1; // e.g. to only print one point every 10 years.
363
364 if (granularity == Dygraph.MONTHLY) {
365 months = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ];
366 } else if (granularity == Dygraph.QUARTERLY) {
367 months = [ 0, 3, 6, 9 ];
368 } else if (granularity == Dygraph.BIANNUAL) {
369 months = [ 0, 6 ];
370 } else if (granularity == Dygraph.ANNUAL) {
371 months = [ 0 ];
372 } else if (granularity == Dygraph.DECADAL) {
373 months = [ 0 ];
374 year_mod = 10;
375 } else if (granularity == Dygraph.CENTENNIAL) {
376 months = [ 0 ];
377 year_mod = 100;
378 } else {
379 Dygraph.warn("Span of dates is too long");
380 }
381
382 var start_year = new Date(start_time).getFullYear();
383 var end_year = new Date(end_time).getFullYear();
384 var zeropad = Dygraph.zeropad;
385 for (var i = start_year; i <= end_year; i++) {
386 if (i % year_mod !== 0) continue;
387 for (var j = 0; j < months.length; j++) {
388 var date_str = i + "/" + zeropad(1 + months[j]) + "/01";
389 t = Dygraph.dateStrToMillis(date_str);
390 if (t < start_time || t > end_time) continue;
391 ticks.push({ v:t,
392 label: formatter(new Date(t), granularity, opts, dg)
393 });
394 }
395 }
396 }
397
398 return ticks;
399 };
400
401 // These are set here so that this file can be included after dygraph.js.
402 Dygraph.DEFAULT_ATTRS.axes.x.ticker = Dygraph.dateTicker;
403 Dygraph.DEFAULT_ATTRS.axes.y.ticker = Dygraph.numericTicks;
404 Dygraph.DEFAULT_ATTRS.axes.y2.ticker = Dygraph.numericTicks;