8000 Contour line labels by alexcjohnson · Pull Request #1815 · plotly/plotly.js · GitHub
[go: up one dir, main page]

Skip to content

Contour line labels #1815

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

Merged
merged 39 commits into from
Jun 30, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
468ef5d
put all contour lines into one group (so we can clip it later)
alexcjohnson Jun 21, 2017
88cc33c
collect contour clipPath in the main <defs>
alexcjohnson Jun 21, 2017
ee7a839
more standard format for contour constants
alexcjohnson Jun 22, 2017
b56f4ea
move lineIntersect -> Lib.geometry2d
alexcjohnson Jun 22, 2017
d534fb2
segmentDistance and tests of geometry2d
alexcjohnson Jun 22, 2017
d1e3448
contour line label basic functionality
alexcjohnson Jun 22, 2017
b8c75c0
better test of alternate Drawing.font syntax
alexcjohnson Jun 23, 2017
2f3a712
use contour/attributes in contourcarpet/attributes
alexcjohnson Jun 23, 2017
6299303
pull path measurement routines out into Lib
alexcjohnson Jun 23, 2017
99f39f8
allow contour labels even without lines
alexcjohnson Jun 23, 2017
d518c83
simple contour label position optimization
alexcjohnson Jun 23, 2017
27f8cfe
use axis formatting for contour labels
alexcjohnson Jun 23, 2017
221b124
include label attrs in contourcarpet to avoid errors but they're noops
alexcjohnson Jun 23, 2017
ca1cced
location -> loc (window global potential confusion)
alexcjohnson Jun 26, 2017
d52cfba
scale min path length for contour labels to width + height
alexcjohnson Jun 26, 2017
0f37648
:cow2: remove obsolete regexp
alexcjohnson Jun 26, 2017
62156dd
:hocho: long-obsolete cache object
alexcjohnson Jun 27, 2017
539ca22
Drawing.bBox "inTester" mode for quicker testing of dummy elements
alexcjohnson Jun 27, 2017
2116a12
contours.font -> contours.labelfont
alexcjohnson Jun 27, 2017
e1880c1
more permissive Drawing.bBox test
alexcjohnson Jun 27, 2017
14c832e
image tests of contour labels
alexcjohnson Jun 27, 2017
1bbdf59
contour line-colored label test
alexcjohnson Jun 27, 2017
e5a2f91
use `editTypes` for contour/contourcarpet-specific attributes
alexcjohnson Jun 27, 2017
cbdf795
no editType nesting - just docalc on editing full containers
alexcjohnson Jun 27, 2017
4db549c
:hocho: obsolete import
alexcjohnson Jun 27, 2017
fb4b690
refactor contour/plot for smaller functions
alexcjohnson Jun 29, 2017
b0f9bb2
updated contour_edge_cases baseline
alexcjohnson Jun 29, 2017
e1caa9e
unify contour.style and contourcarpet.style
alexcjohnson Jun 29, 2017
0ff2dc4
cover contour edge cases with contourcarpet
alexcjohnson Jun 29, 2017
f5873f1
fix contour style when coloring=none
alexcjohnson Jun 29, 2017
b5a674f
a little more stuff contourcarpet can inherit from contour
alexcjohnson Jun 29, 2017
1f85a6f
fix carpet plot clip path
alexcjohnson Jun 30, 2017
6c2043e
:hocho: some obsolete code in carpet/plot
alexcjohnson Jun 30, 2017
bbb9574
update histogram2dcontour for contour.plot API change
alexcjohnson Jun 30, 2017
9495dee
nest scattercontour lines inside a contourlines group
alexcjohnson Jun 30, 2017
7f086e0
fixup font->labelfont in contourcarpet
alexcjohnson Jun 30, 2017
49b8141
labels on contourcarpet
alexcjohnson Jun 30, 2017
8934038
update comment on contourcarpet label bounds
alexcjohnson Jun 30, 2017
dbeecd0
update baselines for findBestTextLocation bugfix
alexcjohnson Jun 30, 2017
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
Prev Previous commit
Next Next commit
contour line label basic functionality
no optimization at all yet
  • Loading branch information
alexcjohnson committed Jun 23, 2017
commit d1e344891b4b7bc31942dc18e367aa315083af83
3 changes: 2 additions & 1 deletion src/plot_api/plot_api.js
Original file line number Diff line number Diff line change
Expand Up @@ -1374,7 +1374,8 @@ function _restyle(gd, aobj, _traces) {
'line.cmin', 'line.cmax',
'marker.line.cmin', 'marker.line.cmax',
'contours.start', 'contours.end', 'contours.size',
'contours.showlines',
'contours.showlines', 'contours.showlabels', 'contours.labelformat',
Copy link
Contributor

Choose a reason for hiding this comment

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

Wanna try adding editType flags their attribute declarations instead as in #1653 ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

@etpinard I had a misstep in e5a2f91 when I thought we could hunt for editType inside containers, but your awesome plot_api tests showed that wasn't going to work - so removed that piece in cbdf795 - look reasonable? Another baby step to cleaning up restyle and relayout...

'contours.font', 'contours.font.family', 'contours.font.size',
'line', 'line.smoothing', 'line.shape',
'error_y.width', 'error_x.width', 'error_x.copy_ystyle',
'marker.maxdisplayed'
Expand Down
27 changes: 27 additions & 0 deletions src/traces/contour/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ var scatterAttrs = require('../scatter/attributes');
var colorscaleAttrs = require('../../components/colorscale/attributes');
var colorbarAttrs = require('../../components/colorbar/attributes');
var dash = require('../../components/drawing/attributes').dash;
var fontAttrs = require('../../plots/font_attributes');
var extendFlat = require('../../lib/extend').extendFlat;

var scatterLineAttrs = scatterAttrs.line;
Expand Down Expand Up @@ -108,6 +109,32 @@ module.exports = extendFlat({}, {
'Determines whether or not the contour lines are drawn.',
'Has only an effect if `contours.coloring` is set to *fill*.'
].join(' ')
},
showlabels: {
valType: 'boolean',
dflt: false,
role: 'style',
description: [
'Determines whether to label the contour lines with their values.'
].join(' ')
},
font: extendFlat({}, fontAttrs, {
Copy link
Contributor

Choose a reason for hiding this comment

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

I'd vote for labelfont here.

cc @cldougl

Copy link
Member

Choose a reason for hiding this comment

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

+1 for labelfont

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

-> labelFont in 2116a12

description: [
'Sets the font used for labeling the contour levels.',
'The default color comes from the lines, if shown.',
// TODO: same size as layout.font, or smaller? 80%?
Copy link
Contributor

Choose a reason for hiding this comment

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

0.8 of layout.font sounds good to me.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I played with that a little, and ended up feeling like that was a little small:
screen shot 2017-06-26 at 4 57 18 pm

Copy link
Contributor

Choose a reason for hiding this comment

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

OK. Let's keep it as 1 * layout.font 👍

'The default family and size come from `layout.font`.'
].join(' ')
}),
labelformat: {
valType: 'string',
dflt: '',
role: 'style',
description: [
'Sets the contour label formatting rule using d3 formatting',
'mini-language which is very similar to Python, see:',
'https://github.com/d3/d3-format/blob/master/README.md#locale_format.'
].join(' ')
}
},

Expand Down
14 changes: 13 additions & 1 deletion src/traces/contour/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,17 @@ module.exports = {

// after one index has been used for a saddle, which do we
// substitute to be used up later?
SADDLEREMAINDER: {1: 4, 2: 8, 4: 1, 7: 13, 8: 2, 11: 14, 13: 7, 14: 11}
SADDLEREMAINDER: {1: 4, 2: 8, 4: 1, 7: 13, 8: 2, 11: 14, 13: 7, 14: 11},

// number of contour levels after which we start increasing the number of
// labels we draw. Many contours means they will generally be close
// together, so it will be harder to follow a long way to find a label
LABELINCREASE: 10,

// minimum length of a contour line, as a multiple of the label length,
// at which we draw *any* labels
LABELMIN: 3,

// max number of labels to draw on a single contour path, no matter how long
LABELMAX: 10
};
194 changes: 192 additions & 2 deletions src/traces/contour/plot.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ var d3 = require('d3');

var Lib = require('../../lib');
var Drawing = require('../../components/drawing');
var svgTextUtils = require('../../lib/svg_text_utils');

var heatmapPlot = require('../heatmap/plot');
var makeCrossings = require('./make_crossings');
var findAllPaths = require('./find_all_paths');
var endPlus = require('./end_plus');
var constants = require('./constants');


module.exports = function plot(gd, plotinfo, cdcontours) {
Expand Down Expand Up @@ -80,7 +82,7 @@ function plotOne(gd, plotinfo, cd) {
var plotGroup = makeContourGroup(plotinfo, cd, id);
makeBackground(plotGroup, perimeter, contours);
makeFills(plotGroup, pathinfo, perimeter, contours);
makeLines(plotGroup, pathinfo, contours);
makeLines(plotGroup, pathinfo, gd, cd[0], contours, perimeter);
clipGaps(plotGroup, plotinfo, fullLayout._defs, cd[0], perimeter);
}

Expand Down Expand Up @@ -259,7 +261,11 @@ function joinAllPaths(pi, perimeter) {
return fullpath;
}

function makeLines(plotgroup, pathinfo, contours) {
var TRAILING_ZEROS = /\.?0+$/;

function makeLines(plotgroup, pathinfo, gd, cd0, contours, perimeter) {
var defs = gd._fullLayout._defs;

var smoothing = pathinfo[0].smoothing;

var lineContainer = plotgroup.selectAll('g.contourlines').data([0]);
Expand Down Expand Up @@ -296,6 +302,190 @@ function makeLines(plotgroup, pathinfo, contours) {
})
.style('stroke-miterlimit', 1)
.style('vector-effect', 'non-scaling-stroke');

var showLabels = contours.showlabels;
var clipId = showLabels ? 'clipline' + cd0.trace.uid : null;

var lineClip = defs.select('.clips').selectAll('#' + clipId)
.data(showLabels ? [0] : []);
lineClip.exit().remove();

lineClip.enter().append('clipPath')
.classed('contourlineclip', true)
.attr('id', clipId);

Drawing.setClipUrl(lineContainer, clipId);

var labelGroup = plotgroup.selectAll('g.contourlabels')
.data(showLabels ? [0] : []);

labelGroup.exit().remove();

labelGroup.enter().append('g')
.classed('contourlabels', true);

if(showLabels) {
var labelClipPathData = straightClosedPath(perimeter);

var labelData = [];

var contourFormat;
if(contours.labelformat) {
contourFormat = d3.format(contours.labelformat);
}
else {
// round to 2 digits past magnitude of contours.size,
// then remove trailing zeroes
var valRound = 2 - Math.floor(Math.log(contours.size) / Math.LN10 + 0.01);
if(valRound <= 0) {
contourFormat = function(v) { return v.toFixed(); };
}
else {
contourFormat = function(v) {
var valStr = v.toFixed(valRound);
return valStr.replace(TRAILING_ZEROS, '');
};
}
}

var dummyText = defs.append('text')
Copy link
Contributor

Choose a reason for hiding this comment

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

Why did you append this dummy text node to <defs> instead of Drawing.tester?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

good question! Actually, I bet if it's already in Drawing.tester we can avoid the [cloneNode and appendChild] steps 🐎

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

🐎 539ca22

.attr('data-notex', 1)
.call(Drawing.font, contours.font);

var plotDiagonal = Math.sqrt(Math.pow(pathinfo[0].xaxis._length, 2) +
Math.pow(pathinfo[0].yaxis._length, 2));

// the path length to use to scale the number of labels to draw:
var normLength = plotDiagonal /
Math.max(1, pathinfo.length / constants.LABELINCREASE);

linegroup.each(function(d) {
// - make a dummy label for this level and calc its bbox
var text = contourFormat(d.level);
dummyText.text(text)
.call(svgTextUtils.convertToTspans, gd);
var bBox = Drawing.bBox(dummyText.node());
var textWidth = bBox.width;
var textHeight = bBox.height;
var dy = (bBox.top + bBox.bottom) / 2;
var textOpts = {
text: text,
width: textWidth,
height: textHeight,
level: d.level,
dy: dy
};

d3.select(this).selectAll('path').each(function() {
var path = this;
var pathLen = path.getTotalLength();

if(pathLen < textWidth * constants.LABELMIN) return;

var labelCount = Math.ceil(pathLen / normLength);
for(var i = 0.5; i < labelCount; i++) {
var positionOnPath = i * pathLen / labelCount;
var loc = getLocation(path, pathLen, positionOnPath, textOpts);
// TODO: no optimization yet: just get display mechanics working
labelClipPathData += addLabel(loc, textOpts, labelData);
}

});
// - iterate over paths for this level, finding the best position(s)
// for label(s) on that path, given all the other labels we've
// already placed
});

dummyText.remove();

var labels = labelGroup.selectAll('text')
.data(labelData, function(d) {
return d.text + ',' + d.x + ',' + d.y + ',' + d.theta;
});

labels.exit().remove();

labels.enter().append('text')
.attr({
'data-notex': 1,
'text-anchor': 'middle'
})
.each(function(d) {
var x = d.x + Math.sin(d.theta) * d.dy;
var y = d.y - Math.cos(d.theta) * d.dy;
d3.select(this)
.text(d.text)
.attr({
x: x,
y: y,
transform: 'rotate(' + (180 * d.theta / Math.PI) + ' ' + x + ' ' + y + ')'
})
.call(svgTextUtils.convertToTspans, gd)
.call(Drawing.font, contours.font.family, contours.font.size);
});

var lineClipPath = lineClip.selectAll('path').data([0]);
lineClipPath.enter().append('path');
lineClipPath.attr('d', labelClipPathData);
}

}

function straightClosedPath(pts) {
return 'M' + pts.join('L') + 'Z';
}

function addLabel(loc, textOpts, labelData) {
var halfWidth = textOpts.width / 2;
var halfHeight = textOpts.height / 2;

var x = loc.x;
var y = loc.y;
var theta = loc.theta;

var sin = Math.sin(theta);
var cos = Math.cos(theta);
var dxw = halfWidth * cos;
var dxh = halfHeight * sin;
var dyw = halfWidth * sin;
var dyh = -halfHeight * cos;
var bBoxPts = [
[x - dxw - dxh, y - dyw - dyh],
[x + dxw - dxh, y + dyw - dyh],
[x + dxw + dxh, y + dyw + dyh],
[x - dxw + dxh, y - dyw + dyh],
];

labelData.push({
text: textOpts.text,
x: x,
y: y,< 10669 /td>
dy: textOpts.dy,
theta: theta,
level: textOpts.level,
width: textOpts.width,
height: textOpts.height
});

return straightClosedPath(bBoxPts);
}

function getLocation(path, pathLen, positionOnPath, textOpts) {
var halfWidth = textOpts.width / 2;

// for the angle, use points on the path separated by the text width
// even though due to curvature, the text will cover a bit more than that
var p0 = path.getPointAtLength(Lib.mod(positionOnPath - halfWidth, pathLen));
var p1 = path.getPointAtLength(Lib.mod(positionOnPath + halfWidth, pathLen));
// note: atan handles 1/0 nicely
var theta = Math.atan((p1.y - p0.y) / (p1.x - p0.x));
// center the text at 2/3 of the center position plus 1/3 the p0/p1 midpoint
// that's the average position of this segment, assuming it's roughly quadratic
var pCenter = path.getPointAtLength(positionOnPath);
var x = (pCenter.x * 4 + p0.x + p1.x) / 6;
var y = (pCenter.y * 4 + p0.y + p1.y) / 6;

return {x: x, y: y, theta: theta};
}

function clipGaps(plotGroup, plotinfo, defs, cd0, perimeter) {
Expand Down
22 changes: 15 additions & 7 deletions src/traces/contour/style.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,31 @@ module.exports = function style(gd) {
});

contours.each(function(d) {
var c = d3.select(this),
trace = d.trace,
contours = trace.contours,
line = trace.line,
cs = contours.size || 1,
start = contours.start;
var c = d3.select(this);
var trace = d.trace;
var contours = trace.contours;
var line = trace.line;
var cs = contours.size || 1;
var start = contours.start;
var colorLines = contours.coloring === 'lines';

var colorMap = makeColorMap(trace);

c.selectAll('g.contourlevel').each(function(d) {
d3.select(this).selectAll('path')
.call(Drawing.lineGroupStyle,
line.width,
contours.coloring === 'lines' ? colorMap(d.level) : line.color,
colorLines ? colorMap(d.level) : line.color,
line.dash);
});

var labelFontColor = (contours.font || {}).color;
c.selectAll('g.contourlabels text').each(function(d) {
Drawing.font(d3.select(this), {
color: labelFontColor || (colorLines ? colorMap(d.level) : line.color)
});
});

var firstFill;

c.selectAll('g.contourfill path')
Expand Down
17 changes: 15 additions & 2 deletions src/traces/contour/style_defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,38 @@
'use strict';

var colorscaleDefaults = require('../../components/colorscale/defaults');
var Lib = require('../../lib');


module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, layout, defaultColor, defaultWidth) {
var coloring = coerce('contours.coloring');

var showLines;
var lineColor = '';
if(coloring === 'fill') showLines = coerce('contours.showlines');

if(showLines !== false) {
if(coloring !== 'lines') coerce('line.color', defaultColor || '#000');
if(coloring !== 'lines') lineColor = coerce('line.color', defaultColor || '#000');
coerce('line.width', defaultWidth === undefined ? 0.5 : defaultWidth);
coerce('line.dash');
}

coerce('line.smoothing');

if((traceOut.contours || {}).coloring !== 'none') {
if(coloring !== 'none') {
colorscaleDefaults(
traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
);
}

var showLabels = coerce('contours.showlabels');
if(showLabels) {
var globalFont = layout.font;
Lib.coerceFont(coerce, 'contours.font', {
family: globalFont.family,
size: globalFont.size,
color: lineColor
});
coerce('contours.labelformat');
}
};
0