Skip to content

Commit 11e3bc7

Browse files
committed
Place auto labels across all traces of a plot area
1 parent 86f6daf commit 11e3bc7

3 files changed

Lines changed: 223 additions & 19 deletions

File tree

‎src/plots/cartesian/index.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -220,11 +220,6 @@ function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback
220220
var layerData = [];
221221
var zoomScaleQueryParts = [];
222222

223-
// Keep the labels of text traces clear of the tick labels that sit inside the plot area
224-
plotinfo.axisLayers = [plotinfo.xaxis, plotinfo.yaxis]
225-
.filter((ax) => (ax.ticklabelposition || '').indexOf('inside') !== -1)
226-
.map((ax) => fullLayout._plots[ax._mainSubplot][ax._id.charAt(0) + 'axislayer']);
227-
228223
// Plot each zorder group in ascending order
229224
for(var z = 0; z < zindices.length; z++) {
230225
var zorder = zindices[z];

‎src/traces/scatter/auto_text_position.js‎

Lines changed: 78 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
const d3 = require('@plotly/d3');
44
const Lib = require('../../lib');
55
const Drawing = require('../../components/drawing');
6+
const Axes = require('../../plots/cartesian/axes');
67
const subTypes = require('./subtypes');
78
const isNumeric = require('fast-isnumeric');
89
const { textrank } = require('./attributes');
@@ -14,49 +15,51 @@ const { textrank } = require('./attributes');
1415
* labels, which `Lib.placeLabels` then places by `textrank`, trace order,
1516
* and data order. The text in `plotinfo.axisLayers` blocks them too.
1617
*
18+
* A cartesian `plot` call draws one zorder group, one carpet, or one overlaid subplot.
19+
* So the pass covers every scatter trace in the plot area of `plotinfo`,
20+
* with the axes of its own subplot. The pass of the last group sees all traces,
21+
* and `_tpAuto` keeps the labels of the earlier passes in place where it can.
22+
*
1723
* Sets `_tpAuto`, `_tpAutoGap`, and `_tpAutoLeader` on every calcdata point
1824
* with an *auto* position and repositions its `<text>` node. Does nothing
19-
* when no trace of the subplot uses *auto*, or in the plot of a range slider,
25+
* when no trace of the plot area uses *auto*, or in the plot of a range slider,
2026
* where labels are never placed.
2127
*
2228
* A label that MathJax has not rendered yet has no box, so it is skipped,
2329
* and the whole pass runs again once every pending render is done.
2430
*
2531
* @param gd - the graph div
2632
* @param plotinfo - the subplot, with `xaxis` and `yaxis`, and optional `axisLayers`, the d3 selections
27-
* of the axis layers that sit inside the plot area
33+
* of the layers with text inside the plot area. A cartesian pass adds the tick labels of its axes.
2834
* @param traceGroups - d3 selection of the `g.trace` groups, bound to calcdata
2935
*/
3036
module.exports = function autoTextPosition(gd, plotinfo, traceGroups) {
3137
// The slider shares the calcdata with the main plot, so a pass here would replace the main plot's results
3238
if (plotinfo.isRangePlot) return;
3339

34-
let hasAuto = false;
35-
traceGroups.each((cd) => {
36-
const trace = cd[0].trace;
37-
if (trace.visible === true && hasAutoTextPosition(trace)) hasAuto = true;
38-
});
40+
const area = plotArea(gd, plotinfo, traceGroups);
41+
const hasAuto = area.traces.some(({ cd }) => cd[0].trace.visible === true && hasAutoTextPosition(cd[0].trace));
3942
if (!hasAuto) return;
4043

4144
const xa = plotinfo.xaxis;
4245
const ya = plotinfo.yaxis;
4346
const markers = [];
4447
// Read the axis text before the label measurements, which write to the tester and force a layout each
45-
const fixed = axisTextBoxes(plotinfo.axisLayers, traceGroups.node());
48+
const fixed = axisTextBoxes(area.axisLayers, traceGroups.node());
4649
const labels = [];
4750
let pending = false;
4851

49-
traceGroups.each(function (cd) {
52+
area.traces.forEach(({ cd, node, xaxis, yaxis }) => {
5053
const trace = cd[0].trace;
5154
if (trace.visible !== true) return;
5255

5356
const hasMarkers = subTypes.hasMarkers(trace);
54-
const tr = d3.select(this);
57+
const tr = d3.select(node);
5558

5659
if (hasMarkers) {
5760
tr.selectAll('path.point').each((d) => {
58-
const x = xa.c2p(d.x);
59-
const y = ya.c2p(d.y);
61+
const x = xaxis.c2p(d.x);
62+
const y = yaxis.c2p(d.y);
6063
const r = d.mrc || 0;
6164
markers.push({ x0: x - r, y0: y - r, x1: x + r, y1: y + r, owner: d });
6265
});
@@ -80,8 +83,8 @@ module.exports = function autoTextPosition(gd, plotinfo, traceGroups) {
8083

8184
const pos = d.tp || trace.textposition;
8285
const rank = Lib.extractOption(d, trace, 'tR', 'textrank');
83-
const x = xa.c2p(d.x);
84-
const y = ya.c2p(d.y);
86+
const x = xaxis.c2p(d.x);
87+
const y = yaxis.c2p(d.y);
8588
const label = {
8689
tx,
8790
trace,
@@ -129,6 +132,67 @@ module.exports = function autoTextPosition(gd, plotinfo, traceGroups) {
129132
}
130133
};
131134

135+
/**
136+
* Collect the scatter traces that share the plot area of a subplot.
137+
*
138+
* A cartesian subplot shares its plot area with every trace on the same main axes.
139+
* These are the traces of the other zorder groups, of the overlaid axes, and of the carpets.
140+
* Any other subplot, such as polar or ternary, has only its own trace groups.
141+
*
142+
* @param gd - the graph div
143+
* @param plotinfo - the subplot, or the stand-in that a carpet trace passes
144+
* @param traceGroups - d3 selection of the `g.trace` groups of the calling `plot` call
145+
* @returns `traces`, the calcdata, `<g>` node, `xaxis` and `yaxis` of each trace,
146+
* and `axisLayers`, the d3 selections of the axis text inside the plot area
147+
*/
148+
function plotArea(gd, plotinfo, traceGroups) {
149+
const isFigureAxis = (ax) => ax && ax._id && Axes.getFromId(gd, ax._id) === ax;
150+
151+
// The axes of polar, ternary, and smith subplots are not axes of the figure
152+
if (!isFigureAxis(plotinfo.xaxis) || !isFigureAxis(plotinfo.yaxis)) {
153+
const traces = [];
154+
traceGroups.each(function (cd) {
155+
traces.push({ cd, node: this, xaxis: plotinfo.xaxis, yaxis: plotinfo.yaxis });
156+
});
157+
return { traces, axisLayers: plotinfo.axisLayers };
158+
}
159+
160+
const fullLayout = gd._fullLayout;
161+
const mainAxis = (ax) => (ax.overlaying && Axes.getFromId(gd, ax.overlaying)) || ax;
162+
const mainX = mainAxis(plotinfo.xaxis);
163+
const mainY = mainAxis(plotinfo.yaxis);
164+
const traces = [];
165+
const axes = new Set([plotinfo.xaxis, plotinfo.yaxis]);
166+
167+
fullLayout._cartesianlayer.selectAll('g.trace.scatter').each(function (cd) {
168+
// A group that the next draw removes belongs to an older calculation
169+
const trace = cd?.[0]?.trace;
170+
if (!trace || !gd._fullData.includes(trace)) return;
171+
172+
// The axis objects of `trace._xA` and `trace._yA` can be older than the last relayout
173+
const axisOf = (letter) => {
174+
const id = cd[0].carpet ? cd[0].carpet[letter + 'axis'] || letter : trace[letter + 'axis'];
175+
return Axes.getFromId(gd, id);
176+
};
177+
const xaxis = axisOf('x');
178+
const yaxis = axisOf('y');
179+
if (!xaxis || !yaxis || mainAxis(xaxis) !== mainX || mainAxis(yaxis) !== mainY) return;
180+
181+
traces.push({ cd, node: this, xaxis, yaxis });
182+
axes.add(xaxis);
183+
axes.add(yaxis);
184+
});
185+
186+
// The tick labels that sit inside the plot area, and any other text that the caller passes
187+
const layers = new Set(plotinfo.axisLayers);
188+
axes.forEach((ax) => {
189+
if ((ax.ticklabelposition || '').includes('inside')) {
190+
layers.add(fullLayout._plots[ax._mainSubplot][ax._id.charAt(0) + 'axislayer']);
191+
}
192+
});
193+
return { traces, axisLayers: [...layers] };
194+
}
195+
132196
/**
133197
* Measure the text in some axis layers, in the frame of the trace groups.
134198
*

‎test/jasmine/tests/scatter_test.js‎

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ var createGraphDiv = require('../assets/create_graph_div');
1212
var destroyGraphDiv = require('../assets/destroy_graph_div');
1313
var customAssertions = require('../assets/custom_assertions');
1414
var negateIf = require('../assets/negate_if');
15+
var selectButton = require('../assets/modebar_button');
1516

1617
var transitions = require('../assets/transitions');
1718

@@ -1226,6 +1227,150 @@ describe('end-to-end scatter tests', function() {
12261227
.then(done, done.fail);
12271228
});
12281229

1230+
describe('in a plot area that several traces share', () => {
1231+
const x = Array.from({ length: 12 }, (_, i) => i);
1232+
const y = x.map((i) => i % 3);
1233+
// A new object for every plot, because a relayout writes its ranges into the layout that the plot got
1234+
const size = () => ({ width: 600, height: 400, showlegend: false });
1235+
const trace = (name, shift, extra) =>
1236+
Lib.extendFlat(
1237+
{
1238+
mode: 'markers+text',
1239+
x: x.map((i) => i + shift),
1240+
y: y.map((v) => v + shift * 0.8),
1241+
text: x.map((i) => name + i),
1242+
textposition: 'auto',
1243+
marker: { size: 12 }
1244+
},
1245+
extra
1246+
);
1247+
1248+
// Labels that sit on a marker or on another label, among all the traces of the plot
1249+
function collisions() {
1250+
const markers = [];
1251+
d3SelectAll('.point').each(function () {
1252+
markers.push(this.getBoundingClientRect());
1253+
});
1254+
const labels = visibleLabelBoxes();
1255+
let onMarkers = 0;
1256+
labels.forEach((l) =>
1257+
markers.forEach((m) => {
1258+
if (l.left < m.right && l.right > m.left && l.top < m.bottom && l.bottom > m.top) onMarkers++;
1259+
})
1260+
);
1261+
return { labels: labels.length, onMarkers, onLabels: countOverlaps(labels) };
1262+
}
1263+
1264+
function expectClear(msg) {
1265+
const c = collisions();
1266+
expect(c.labels).toBe(24, msg + ': visible labels');
1267+
expect(c.onMarkers).toBe(0, msg + ': labels on markers');
1268+
expect(c.onLabels).toBe(0, msg + ': labels on labels');
1269+
}
1270+
1271+
it('should keep the labels of different zorder groups apart', (done) => {
1272+
Plotly.newPlot(gd, [trace('A', 0, { zorder: 0 }), trace('B', 0.15, { zorder: 1 })], size())
1273+
.then(() => {
1274+
expectClear('zorder groups');
1275+
return Plotly.relayout(gd, 'xaxis.range', [-1, 8]);
1276+
})
1277+
.then(() => {
1278+
const c = collisions();
1279+
expect(c.onMarkers).toBe(0, 'labels on markers after a zoom');
1280+
expect(c.onLabels).toBe(0, 'labels on labels after a zoom');
1281+
})
1282+
.then(done, done.fail);
1283+
});
1284+
1285+
// Leaders whose label sits away from the end of the leader line
1286+
function detachedLeaders() {
1287+
let n = 0;
1288+
d3SelectAll('.textpoint').each(function () {
1289+
const leader = this.querySelector('path.textleader');
1290+
if (!leader || this.style.display === 'none') return;
1291+
const l = leader.getBoundingClientRect();
1292+
const t = this.querySelector('text').getBoundingClientRect();
1293+
const dx = Math.max(t.left - l.right, l.left - t.right, 0);
1294+
const dy = Math.max(t.top - l.bottom, l.top - t.bottom, 0);
1295+
if (Math.hypot(dx, dy) > 3) n++;
1296+
});
1297+
return n;
1298+
}
1299+
1300+
it('should place the labels again after a pan and a reset of the axes', (done) => {
1301+
Plotly.newPlot(gd, [trace('A', 0, { zorder: 0 }), trace('B', 0.15, { zorder: 1 })], size())
1302+
.then(() => {
1303+
expectClear('before the pan');
1304+
expect(d3SelectAll('.textpoint path.textleader').size()).toBe(24, 'leaders before the pan');
1305+
return Plotly.relayout(gd, 'xaxis.range', [3, 15]);
1306+
})
1307+
.then(
1308+
() =>
1309+
new Promise((resolve) => {
1310+
gd.once('plotly_relayout', resolve);
1311+
selectButton(gd._fullLayout._modeBar, 'resetScale2d').click();
1312+
})
1313+
)
1314+
.then(() => {
1315+
expectClear('after the reset');
1316+
expect(d3SelectAll('.textpoint path.textleader').size()).toBe(24, 'leaders after the reset');
1317+
expect(detachedLeaders()).toBe(0, 'leaders away from their labels');
1318+
})
1319+
.then(done, done.fail);
1320+
});
1321+
1322+
it('should keep the labels of overlaid axes apart', (done) => {
1323+
Plotly.newPlot(gd, [trace('A', 0), trace('B', 0.15, { yaxis: 'y2' })], {
1324+
...size(),
1325+
yaxis2: { overlaying: 'y' }
1326+
})
1327+
.then(() => expectClear('overlaid axes'))
1328+
.then(done, done.fail);
1329+
});
1330+
1331+
it('should keep the labels of a scatter trace and a scattercarpet trace apart', (done) => {
1332+
const carpet = { type: 'carpet', carpet: 'c', a: [1, 2, 3], b: [1, 2, 3], y: [[1, 2, 3], [2, 3, 4], [3, 4, 5]] };
1333+
const onCarpet = {
1334+
type: 'scattercarpet',
1335+
carpet: 'c',
1336+
a: x.map((i) => 1 + (i % 6) / 3),
1337+
b: x.map((i) => 1 + Math.floor(i / 6)),
1338+
mode: 'markers+text',
1339+
text: x.map((i) => 'C' + i),
1340+
textposition: 'auto',
1341+
marker: { size: 12 }
1342+
};
1343+
1344+
Plotly.newPlot(gd, [carpet, onCarpet], size())
1345+
.then(() => {
1346+
// Put a scatter point 7px to the right of and 5px below every carpet point
1347+
const xa = gd._fullLayout.xaxis;
1348+
const ya = gd._fullLayout.yaxis;
1349+
const cd = gd.calcdata.find((c) => c[0].trace.type === 'scattercarpet');
1350+
const near = {
1351+
x: cd.map((d) => xa.p2c(xa.c2p(d.x) + 7)),
1352+
y: cd.map((d) => ya.p2c(ya.c2p(d.y) + 5)),
1353+
text: x.map((i) => 'S' + i)
1354+
};
1355+
return Plotly.newPlot(gd, [carpet, onCarpet, trace('S', 0, near)], size());
1356+
})
1357+
.then(() => expectClear('scatter and scattercarpet'))
1358+
.then(done, done.fail);
1359+
});
1360+
1361+
it('should leave no label of a trace that a redraw removes', (done) => {
1362+
Plotly.newPlot(gd, [trace('A', 0, { zorder: 0 }), trace('B', 0.15, { zorder: 1 })], size())
1363+
.then(() => Plotly.react(gd, [trace('A', 0, { zorder: 0 })], size()))
1364+
.then(() => {
1365+
expect(d3SelectAll('.textpoint').size()).toBe(12, 'label nodes');
1366+
const c = collisions();
1367+
expect(c.labels).toBe(12, 'visible labels');
1368+
expect(c.onMarkers).toBe(0, 'labels on markers');
1369+
})
1370+
.then(done, done.fail);
1371+
});
1372+
});
1373+
12291374
describe('in a subplot with axis labels inside the plot area', () => {
12301375
const size = { width: 480, height: 440, margin: { l: 50, r: 50, t: 50, b: 50 }, showlegend: false };
12311376
const names = (n) => Array.from({ length: n }, (_, i) => 'pt ' + i);

0 commit comments

Comments
 (0)