Improved number format function. Also improved the generation of small tick values

This commit is contained in:
etimberg 2015-10-23 22:00:59 -04:00
parent 3a20d1187e
commit 0c3d9ec5dd
3 changed files with 57 additions and 4 deletions

View File

@ -138,7 +138,7 @@
if (this.options.ticks.userCallback) {
return this.options.ticks.userCallback(numericalTick, index, ticks);
}
return this.options.ticks.callback(numericalTick);
return this.options.ticks.callback(numericalTick, index, ticks);
},
this);
},

View File

@ -7,6 +7,32 @@
var defaultConfig = {
position: "left",
ticks: {
callback: function(tickValue, index, ticks) {
var delta = ticks[1] - ticks[0];
// If we have a number like 2.5 as the delta, figure out how many decimal places we need
if (Math.abs(delta) > 1) {
if (tickValue !== Math.floor(tickValue)) {
// not an integer
delta = tickValue - Math.floor(tickValue);
}
}
var logDelta = helpers.log10(Math.abs(delta));
var tickString = '';
if (tickValue !== 0) {
var numDecimal = -1 * Math.floor(logDelta);
numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
tickString = tickValue.toFixed(numDecimal);
} else {
tickString = '0'; // never show decimal places for 0
}
return tickString;
}
}
};
var LinearScale = Chart.Scale.extend({
@ -119,9 +145,11 @@
var niceMin = Math.floor(this.min / spacing) * spacing;
var niceMax = Math.ceil(this.max / spacing) * spacing;
var numSpaces = Math.ceil((niceMax - niceMin) / spacing);
// Put the values into the ticks array
for (var j = niceMin; j <= niceMax; j += spacing) {
this.ticks.push(j);
for (var j = 0; j <= numSpaces; ++j) {
this.ticks.push(niceMin + (j * spacing));
}
if (this.options.position == "left" || this.options.position == "right") {

View File

@ -412,6 +412,31 @@ describe('Linear Scale', function() {
expect(scale.ticks).toEqual(['80', '70', '60', '50', '40', '30', '20', '10', '0']);
});
it('should use the correct number of decimal places in the default format function', function() {
var scaleID = 'myScale';
var mockData = {
datasets: [{
yAxisID: scaleID,
data: [0.06, 0.005, 0, 0.025, 0.0078]
}, ]
};
var mockContext = window.createMockContext();
var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('linear'));
var Constructor = Chart.scaleService.getScaleConstructor('linear');
var scale = new Constructor({
ctx: mockContext,
options: config,
data: mockData,
id: scaleID
});
// Set arbitrary width and height for now
scale.update(50, 400);
expect(scale.ticks).toEqual(['0.06', '0.05', '0.04', '0.03', '0.02', '0.01', '0']);
});
it('Should build labels using the user supplied callback', function() {
var scaleID = 'myScale';
@ -423,7 +448,7 @@ describe('Linear Scale', function() {
};
var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('linear'));
config.ticks.userCallback = function(value, index) {
config.ticks.callback = function(value, index) {
return index.toString();
};