Skip to content

Extend axis tickformat/hoverformat configuration #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions src/lib/dates.js
Original file line number Diff line number Diff line change
Expand Up @@ -451,20 +451,48 @@ function yearMonthDayFormatWorld(cDate) { return cDate.formatDate('M d, yyyy');
* tr: tickround ('y', 'm', 'd', 'M', 'S', or # digits)
* used if no explicit fmt is provided
* calendar: optional string, the world calendar system to use
* dtick: optional string or number, side of tick for custom formatting
*
* returns the date/time as a string, potentially with the leading portion
* on a separate line (after '\n')
* Note that this means if you provide an explicit format which includes '\n'
* the axis may choose to strip things after it when they don't change from
* one tick to the next (as it does with automatic formatting)
*/
exports.formatDate = function(x, fmt, tr, calendar) {
exports.formatDate = function(x, fmt, tr, calendar, dtick) {
var headStr,
dateStr;

calendar = isWorldCalendar(calendar) && calendar;

if(fmt) return modDateFormat(fmt, x, calendar);
if(fmt) {
if(typeof fmt === 'string') return modDateFormat(fmt, x, calendar);
if(typeof fmt === 'object') {
var unit = '';
if(typeof dtick === 'string') {
if(Number(dtick.replace('M', '')) > 6) {
unit = 'year';
} else if(Number(dtick.replace('M', '')) >= 1) {
unit = 'month';
}
} else if(dtick >= ONEDAY * 7) {
unit = 'week';
} else if(dtick >= ONEDAY) {
unit = 'day';
} else if(dtick >= ONEHOUR) {
unit = 'hour';
} else if(dtick >= ONEMIN) {
unit = 'minute';
} else if(dtick >= ONESEC) {
unit = 'second';
} else if(dtick >= 0) {
unit = 'millisecond';
}
if(fmt[unit]) {
return modDateFormat(fmt[unit], x, calendar);
}
}
}

if(calendar) {
try {
Expand Down
2 changes: 1 addition & 1 deletion src/plots/cartesian/axes.js
Original file line number Diff line number Diff line change
Expand Up @@ -1250,7 +1250,7 @@ function formatDate(ax, out, hover, extraPrecision) {
else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr];
}

var dateStr = Lib.formatDate(out.x, fmt, tr, ax.calendar),
var dateStr = Lib.formatDate(out.x, fmt, tr, ax.calendar, ax.dtick),
headStr;

var splitIndex = dateStr.indexOf('\n');
Expand Down
7 changes: 5 additions & 2 deletions src/plots/cartesian/layout_attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ module.exports = {
].join(' ')
},
tickformat: {
valType: 'string',
valType: 'any',
dflt: '',
role: 'style',
description: [
Expand All @@ -445,7 +445,10 @@ module.exports = {
'https://github.com/d3/d3-time-format/blob/master/README.md#locale_format',
'We add one item to d3\'s date formatter: *%{n}f* for fractional seconds',
'with n digits. For example, *2016-10-13 09:15:23.456* with tickformat',
'*%H~%M~%S.%2f* would display *09~15~23.46*'
'*%H~%M~%S.%2f* would display *09~15~23.46* Also now you can specify date',
'format for each zooming level independently using following configuration',
'object {hour: *%H:%M*, day: *%e %b*}. Available following zooming levels:',
'year, month, week, day, hour, minute, second, millisecond'
].join(' ')
},
hoverformat: {
Expand Down
3 changes: 2 additions & 1 deletion tasks/util/strict_d3.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ var pathToStrictD3Module = path.join(
constants.pathToImageTest,
'strict-d3.js'
);
var normalizedPathToStrictD3Module = pathToStrictD3Module.replace(/\\/g, '/'); // replacing of "\" for windows users

/**
* Transform `require('d3')` expressions to `require(/path/to/strict-d3.js)`
Expand All @@ -18,7 +19,7 @@ module.exports = transformTools.makeRequireTransform('requireTransform',
var pathOut;

if(pathIn === 'd3' && opts.file !== pathToStrictD3Module) {
pathOut = 'require(\'' + pathToStrictD3Module + '\')';
pathOut = 'require(\'' + normalizedPathToStrictD3Module + '\')';
}

if(pathOut) return cb(null, pathOut);
Expand Down
Binary file added test/image/baselines/custom_tickformat.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 23 additions & 0 deletions test/image/mocks/custom_tickformat.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"data": [
{
"x": ["2010-01-01","2010-01-02","2010-01-03","2010-01-04","2010-01-05","2010-01-06","2010-01-07"],
"y": [-5,3,-1,7,-1,3,-5]
}
],
"layout": {
"title": "tickformat",
"xaxis": {
"tickformat": {
"millisecond": "%H:%M:%S.%L ms",
"second": "%H:%M:%S s",
"minute": "%H:%M m",
"hour": "%H:%M h",
"day": "%e %b d",
"week": "%b %d w",
"month": "%b %y M",
"year": "%Y Y"
}
}
}
}
138 changes: 138 additions & 0 deletions test/jasmine/tests/custom_tickformat_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
var Plotly = require('@lib/index');
var Lib = require('@src/lib');
var Axes = require('@src/plots/cartesian/axes');
var Fx = require('@src/components/fx');
var d3 = require('d3');
var createGraphDiv = require('../assets/create_graph_div');
var destroyGraphDiv = require('../assets/destroy_graph_div');
var selectButton = require('../assets/modebar_button');
var constants = require('@src/constants/numerical');

var mock = require('@mocks/custom_tickformat.json');
var tickFormat = mock.layout.xaxis.tickformat;

function getZoomInButton(gd) {
return selectButton(gd._fullLayout._modeBar, 'zoomIn2d');
}

function getZoomOutButton(gd) {
return selectButton(gd._fullLayout._modeBar, 'zoomOut2d');
}

function getFormatter(dtick) {
var unit = '';
if(typeof dtick === 'string') {
if(Number(dtick.replace('M', '')) > 6) {
unit = 'year';
} else if(Number(dtick.replace('M', '')) >= 1) {
unit = 'month';
}
} else if(dtick >= constants.ONEDAY * 7) {
unit = 'week';
} else if(dtick >= constants.ONEDAY) {
unit = 'day';
} else if(dtick >= constants.ONEHOUR) {
unit = 'hour';
} else if(dtick >= constants.ONEMIN) {
unit = 'minute';
} else if(dtick >= constants.ONESEC) {
unit = 'second';
} else if(dtick >= 0) {
unit = 'millisecond';
}
if(tickFormat[unit]) {
return d3.time.format.utc(tickFormat[unit]);
}
return function(mock) {return mock;};
}

describe('Test extended tickformat:', function() {

var mockCopy, gd;

beforeEach(function() {
gd = createGraphDiv();
mockCopy = Lib.extendDeep({}, mock);
});

afterEach(destroyGraphDiv);

it('Zooming-in until milliseconds zoom level', function(done) {
var promise = Plotly.plot(gd, mockCopy.data, mockCopy.layout);

var zoomIn = function() {
promise = promise.then(function() {
getZoomInButton(gd).click();
var xLabels = Axes.calcTicks(gd._fullLayout.xaxis);
var formatter = getFormatter(gd._fullLayout.xaxis.dtick);
var expectedLabels = xLabels.map(function(d) {return formatter(new Date(d.x));});
var actualLabels = xLabels.map(function(d) {return d.text;});
expect(expectedLabels).toEqual(actualLabels);
if(gd._fullLayout.xaxis.dtick > 1) {
zoomIn();
} else {
done();
}
});
};
zoomIn();
});

it('Zooming-out until years zoom level', function(done) {
var promise = Plotly.plot(gd, mockCopy.data, mockCopy.layout);

var zoomOut = function() {
promise = promise.then(function() {
getZoomOutButton(gd).click();
var xLabels = Axes.calcTicks(gd._fullLayout.xaxis);
var formatter = getFormatter(gd._fullLayout.xaxis.dtick);
var expectedLabels = xLabels.map(function(d) {return formatter(new Date(d.x));});
var actualLabels = xLabels.map(function(d) {return d.text;});
expect(expectedLabels).toEqual(actualLabels);
if(typeof gd._fullLayout.xaxis.dtick === 'number' ||
typeof gd._fullLayout.xaxis.dtick === 'string' && parseInt(gd._fullLayout.xaxis.dtick.replace(/\D/g, '')) < 48) {
zoomOut();
} else {
done();
}
});
};
zoomOut();
});

describe('Check tickformat for hover', function() {
'use strict';

var evt = { xpx: 270, ypx: 10 };

afterEach(destroyGraphDiv);

beforeEach(function() {
gd = createGraphDiv();
mockCopy = Lib.extendDeep({}, mock);
});

it('tickformat for hover and xaxes should coincide', function(done) {
var mockCopy = Lib.extendDeep({}, mock);

Plotly.plot(gd, mockCopy.data, mockCopy.layout).then(function() {
Fx.hover(gd, evt, 'xy');

var hoverTrace = gd._hoverdata[0];
var formatter = getFormatter(gd._fullLayout.xaxis.dtick);

expect(hoverTrace.curveNumber).toEqual(0);
expect(hoverTrace.pointNumber).toEqual(3);
expect(hoverTrace.x).toEqual('2010-01-04');
expect(hoverTrace.y).toEqual(7);

expect(d3.selectAll('g.axistext').size()).toEqual(1);
expect(d3.selectAll('g.hovertext').size()).toEqual(1);
expect(d3.selectAll('g.axistext').select('text').html()).toEqual(formatter(new Date(hoverTrace.x)));
expect(d3.selectAll('g.hovertext').select('text').html()).toEqual('7');
done();
});
});
});

});