') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); Add `tickson: 'boundaries'` for category cartesian axes by etpinard · Pull Request #3275 · plotly/plotly.js · GitHub
Skip to content
1 change: 1 addition & 0 deletions src/components/colorbar/draw.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -198,6 +198,7 @@ module.exports = function draw(gd, id) {
letter: 'y',
font: fullLayout.font,
noHover: true,
noTickson: true,
Comment thread
alexcjohnson marked this conversation as resolved.
calendar: fullLayout.calendar // not really necessary (yet?)
};

Expand Down
107 changes: 81 additions & 26 deletions src/plots/cartesian/axes.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1163,6 +1163,20 @@ function formatCategory(ax, out) {
var tt = ax._categories[Math.round(out.x)];
if(tt === undefined) tt = '';
out.text = String(tt);

// Setup ticks and grid lines boundaries
// at 1/2 a 'category' to the left/bottom
if(ax.tickson === 'boundaries') {
var inbounds = function(v) {
var p = ax.l2p(v);
return p >= 0 && p <= ax._length ? v : null;
};

out.xbnd = [
inbounds(out.x - 0.5),
inbounds(out.x + ax.dtick - 0.5)
];
}
}

function formatLinear(ax, out, hover, extraPrecision, hideexp) {
Expand DownExpand Up@@ -1610,14 +1624,41 @@ axes.drawOne = function(gd, ax, opts) {
var subplotsWithAx = axes.getSubplots(gd, ax);

var vals = ax._vals = axes.calcTicks(ax);
// We remove zero lines, grid lines, and inside ticks if they're within 1px of the end
// The key case here is removing zero lines when the axis bound is zero
var valsClipped = ax._valsClipped = axes.clipEnds(ax, vals);

if(!ax.visible) return;

var transFn = axes.makeTransFn(ax);

// We remove zero lines, grid lines, and inside ticks if they're within 1px of the end
// The key case here is removing zero lines when the axis bound is zero
var valsClipped;
var tickVals;
var gridVals;

if(ax.tickson === 'boundaries' && vals.length) {
// valsBoundaries is not used for labels;
// no need to worry about the other tickTextObj keys
var valsBoundaries = [];
var _push = function(d, bndIndex) {
var xb = d.xbnd[bndIndex];
if(xb !== null) {
valsBoundaries.push(Lib.extendFlat({}, d, {x: xb}));
}
};
for(i = 0; i < vals.length; i++) _push(vals[i], 0);
_push(vals[i - 1], 1);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice solution, keeping xbnd with the rest of the tick calculations.


valsClipped = axes.clipEnds(ax, valsBoundaries);
tickVals = ax.ticks === 'inside' ? valsClipped : valsBoundaries;
gridVals = valsClipped;
} else {
valsClipped = axes.clipEnds(ax, vals);
tickVals = ax.ticks === 'inside' ? valsClipped : vals;
gridVals = valsClipped;
}

ax._valsClipped = valsClipped;

if(!fullLayout._hasOnlyLargeSploms) {
// keep track of which subplots (by main conteraxis) we've already
// drawn grids for, so we don't overdraw overlaying subplots
Expand All@@ -1637,7 +1678,7 @@ axes.drawOne = function(gd, ax, opts) {
'M' + counterAxis._offset + ',0h' + counterAxis._length;

axes.drawGrid(gd, ax, {
vals: valsClipped,
vals: gridVals,
layer: plotinfo.gridlayer.select('.' + axId),
path: gridPath,
transFn: transFn
Expand All@@ -1652,7 +1693,6 @@ axes.drawOne = function(gd, ax, opts) {
}

var tickSigns = axes.getTickSigns(ax);
var tickVals = ax.ticks === 'inside' ? valsClipped : vals;
var tickSubplots = [];

if(ax.ticks) {
Expand DownExpand Up@@ -1920,8 +1960,9 @@ axes.makeTickPath = function(ax, shift, sgn) {
axes.makeLabelFns = function(ax, shift, angle) {
var axLetter = ax._id.charAt(0);
var pad = (ax.linewidth || 1) / 2;
var ticksOnOutsideLabels = ax.tickson !== 'boundaries' && ax.ticks === 'outside';

var labelStandoff = ax.ticks === 'outside' ? ax.ticklen : 0;
var labelStandoff = ticksOnOutsideLabels ? ax.ticklen : 0;
var labelShift = 0;

if(angle && ax.ticks === 'outside') {
Expand All@@ -1930,7 +1971,7 @@ axes.makeLabelFns = function(ax, shift, angle) {
labelShift = ax.ticklen * Math.sin(rad);
}

if(ax.showticklabels && (ax.ticks === 'outside' || ax.showline)) {
if(ax.showticklabels && (ticksOnOutsideLabels || ax.showline)) {
labelStandoff += 0.2 * ax.tickfont.size;
}

Expand DownExpand Up@@ -2018,7 +2059,6 @@ axes.drawTicks = function(gd, ax, opts) {
ticks.attr('transform', opts.transFn);
};


/**
* Draw axis grid
*
Expand DownExpand Up@@ -2151,8 +2191,6 @@ axes.drawLabels = function(gd, ax, opts) {
var tickLabels = opts.layer.selectAll('g.' + cls)
.data(ax.showticklabels ? vals : [], makeDataFn(ax));

var maxFontSize = 0;
var autoangle = 0;
var labelsReady = [];

tickLabels.enter().append('g')
Expand DownExpand Up@@ -2187,10 +2225,6 @@ axes.drawLabels = function(gd, ax, opts) {

tickLabels.exit().remove();

tickLabels.each(function(d) {
maxFontSize = Math.max(maxFontSize, d.fontSize);
});

ax._tickLabels = tickLabels;

// TODO ??
Expand DownExpand Up@@ -2273,16 +2307,20 @@ axes.drawLabels = function(gd, ax, opts) {
// check for auto-angling if x labels overlap
// don't auto-angle at all for log axes with
// base and digit format
if(axLetter === 'x' && !isNumeric(ax.tickangle) &&
if(vals.length && axLetter === 'x' && !isNumeric(ax.tickangle) &&
(ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')
) {
var maxFontSize = 0;
var lbbArray = [];
var i;

tickLabels.each(function(d) {
var s = d3.select(this);
var thisLabel = s.select('.text-math-group');
if(thisLabel.empty()) thisLabel = s.select('text');

maxFontSize = Math.max(maxFontSize, d.fontSize);

var x = ax.l2p(d.x);
var bb = Drawing.bBox(thisLabel.node());

Expand All@@ -2298,21 +2336,38 @@ axes.drawLabels = function(gd, ax, opts) {
});
});

for(var i = 0; i < lbbArray.length - 1; i++) {
if(Lib.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) {
// any overlap at all - set 30 degrees
autoangle = 30;
break;
var autoangle = 0;

if(ax.tickson === 'boundaries') {
var gap = 2;
if(ax.ticks) gap += ax.tickwidth / 2;

for(i = 0; i < lbbArray.length; i++) {
var xbnd = vals[i].xbnd;
var lbb = lbbArray[i];
if(
(xbnd[0] !== null && (lbb.left - ax.l2p(xbnd[0])) < gap) ||
(xbnd[1] !== null && (ax.l2p(xbnd[1]) - lbb.right) < gap)
) {
autoangle = 90;
break;
}
}
} else {
var vLen = vals.length;
var tickSpacing = Math.abs((vals[vLen - 1].x - vals[0].x) * ax._m) / (vLen - 1);
var fitBetweenTicks = tickSpacing < maxFontSize * 2.5;

// any overlap at all - set 30 degrees or 90 degrees
for(i = 0; i < lbbArray.length - 1; i++) {
if(Lib.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) {
autoangle = fitBetweenTicks ? 90 : 30;
break;
}
}
}

if(autoangle) {
var tickspacing = Math.abs(
(vals[vals.length - 1].x - vals[0].x) * ax._m
) / (vals.length - 1);
if(tickspacing < maxFontSize * 2.5) {
autoangle = 90;
}
positionLabels(tickLabels, autoangle);
}
ax._lastangle = autoangle;
Expand Down
6 changes: 6 additions & 0 deletions src/plots/cartesian/axis_defaults.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ var setConvert = require('./set_convert');
* outerTicks: boolean, should ticks default to outside?
* showGrid: boolean, should gridlines be shown by default?
* noHover: boolean, this axis doesn't support hover effects?
* noTickson: boolean, this axis doesn't support 'tickson'
* data: the plot data, used to manage categories
* bgColor: the plot background color, to calculate default gridline colors
*/
Expand DownExpand Up@@ -89,5 +90,10 @@ module.exports = function handleAxisDefaults(containerIn, containerOut, coerce,

if(options.automargin) coerce('automargin');

if(!options.noTickson &&
containerOut.type === 'category' && (containerOut.ticks || containerOut.showgrid)) {
coerce('tickson');
}

return containerOut;
};
14 changes: 14 additions & 0 deletions src/plots/cartesian/layout_attributes.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -304,6 +304,20 @@ module.exports = {
'the axis lines.'
].join(' ')
},
tickson: {
valType: 'enumerated',
values: ['labels', 'boundaries'],
role: 'info',
dflt: 'labels',
editType: 'ticks',
Comment thread
alexcjohnson marked this conversation as resolved.
description: [
'Determines where ticks and grid lines are drawn with respect to their',
'corresponding tick labels.',
'Only has an effect for axes of `type` *category*.',
'When set to *boundaries*, ticks and grid lines are drawn half a category',
'to the left/bottom of labels.'
].join(' ')
},
mirror: {
valType: 'enumerated',
values: [true, 'ticks', false, 'all', 'allticks'],
Expand Down
1 change: 1 addition & 0 deletions src/plots/gl3d/layout/axis_defaults.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, options) {
letter: axName[0],
data: options.data,
showGrid: true,
noTickson: true,
bgColor: options.bgColor,
calendar: options.calendar
},
Expand Down
Binary file addedtest/image/baselines/tickson_boundaries.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
104 changes: 104 additions & 0 deletions test/image/mocks/tickson_boundaries.json
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
{
"data": [
{
"type": "box",
"x": ["day 1", "day 1", "day 1", "day 1", "day 1", "day 1", "day 2", "day 2", "day 2", "day 2", "day 2", "day 2"],
"y": [0.2, 0.2, 0.6, 1, 0.5, 0.4, 0.2, 0.7, 0.9, 0.1, 0.5, 0.3]
},
{
"type": "box",
"x": ["day 1", "day 1", "day 1", "day 1", "day 1", "day 1", "day 2", "day 2", "day 2", "day 2", "day 2", "day 2"],
"y": [0.1, 0.3, 0.1, 0.9, 0.6, 0.6, 0.9, 1, 0.3, 0.6, 0.8, 0.5]
},
{
"type": "box",
"x": ["day 1", "day 1", "day 1", "day 1", "day 1", "day 1", "day 2", "day 2", "day 2", "day 2", "day 2", "day 2"],
"y": [0.6, 0.7, 0.3, 0.6, 0, 0.5, 0.7, 0.9, 0.5, 0.8, 0.7, 0.2]
},

{
"type": "bar",
"x": [1, 2, 1],
"y": ["apples", "bananas", "clementines"],
"orientation": "h",
"xaxis": "x2",
"yaxis": "y2"
},
{
"type": "bar",
"x": [1.3, 2.2, 0.8],
"y": ["apples", "bananas", "clementines"],
"orientation": "h",
"xaxis": "x2",
"yaxis": "y2"
},
{
"type": "bar",
"x": [3, 3.2, 1.8],
"y": ["apples", "bananas", "clementines"],
"orientation": "h",
"xaxis": "x2",
"yaxis": "y2"
},

{
"type": "bar",
"name": "with dtick !== 1",
"x": ["a", "b", "c", "d", "e", "f", "g", "h"],
"y": [1, 2, 1, 2, 1, 3, 4, 1],
"xaxis": "x3",
"yaxis": "y3"
},

{
"mode": "markers",
"marker": {"symbol": "square"},
"name": "with overlapping tick labels",
"x": ["A very long title", "short", "Another very long title"],
"y": [1, 4, 2],
"xaxis": "x4",
"yaxis": "y4"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, just squeaks in unrotated if we draw this without tickson: 'boundaries' 🎉
screen shot 2018-11-26 at 1 20 37 pm

}
],
"layout": {
"boxmode": "group",
"grid": {
"rows": 4,
"columns": 1,
"pattern": "independent",
"ygap": 0.2
},
"xaxis": {
"ticks": "outside",
"tickson": "boundaries",
"gridcolor": "white",
"gridwidth": 4
},
"yaxis2": {
"ticks": "inside",
"tickson": "boundaries",
"gridcolor": "white",
"gridwidth": 4
},
"xaxis3": {
"ticks": "inside",
"tickson": "boundaries",
"gridcolor": "white",
"gridwidth": 4,
"dtick": 2
},
"xaxis4": {
"domain": [0.22, 0.78],
"ticks": "outside",
"ticklen": 20,
"tickson": "boundaries",
"gridcolor": "white",
"gridwidth": 4
},
"plot_bgcolor": "lightgrey",
"showlegend": false,
"width": 500,
"height": 800,
"margin": {"b": 140}
}
}
Loading