Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ed3f1c1

Browse files
committed
improve axis tick increment to reduce precision errors
1 parent 1e479e6 commit ed3f1c1

File tree

4 files changed

+812
-1
lines changed

4 files changed

+812
-1
lines changed

src/lib/increment.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Copyright 2012-2020, Plotly, Inc.
3+
* All rights reserved.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
10+
'use strict';
11+
12+
module.exports = function incrementNumeric(x, delta) {
13+
if(!delta) return x;
14+
15+
// Note 1:
16+
// 0.3 != 0.1 + 0.2 == 0.30000000000000004
17+
// but 0.3 == (10 * 0.1 + 10 * 0.2) / 10
18+
// Attempt to use integer steps to increment
19+
var scale = 1 / Math.abs(delta);
20+
if(scale < 1) scale = 1;
21+
var newX = (
22+
scale * x +
23+
scale * delta
24+
) / scale;
25+
26+
// Note 2:
27+
// now we may also consider rounding to cover few more edge cases
28+
// e.g. 0.3 * 3 = 0.8999999999999999
29+
var lenDt = ('' + delta).length;
30+
var lenX0 = ('' + x).length;
31+
var lenX1 = ('' + newX).length;
32+
33+
if(lenX1 >= lenX0 + lenDt) { // likely a rounding error!
34+
newX = +parseFloat(newX).toPrecision(12);
35+
}
36+
37+
return newX;
38+
};

src/lib/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,8 @@ lib.filterUnique = require('./filter_unique');
158158
lib.filterVisible = require('./filter_visible');
159159
lib.pushUnique = require('./push_unique');
160160

161+
lib.increment = require('./increment');
162+
161163
lib.cleanNumber = require('./clean_number');
162164

163165
lib.ensureNumber = function ensureNumber(v) {

src/plots/cartesian/axes.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1063,7 +1063,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) {
10631063
var axSign = axrev ? -1 : 1;
10641064

10651065
// includes linear, all dates smaller than month, and pure 10^n in log
1066-
if(isNumeric(dtick)) return x + axSign * dtick;
1066+
if(isNumeric(dtick)) return Lib.increment(x, axSign * dtick);
10671067

10681068
// everything else is a string, one character plus a number
10691069
var tType = dtick.charAt(0);

0 commit comments

Comments
 (0)