Skip to content
Open
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
4 changes: 4 additions & 0 deletions draftlogs/7888_add.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- Add Sankey trace link labels [[#7888](https://github.com/plotly/plotly.js/pull/7888)]
- `link.textinfo` shows `label` and/or `value` directly on each link, opt-in and off by default
- `link.texttemplate` allows full custom formatting, with `%{label}`, `%{value}`, `%{valueLabel}`, `%{source.label}`, `%{target.label}`, `%{customdata}` and `%{meta}` as available variables, resolved using the layout locale
- `link.texttemplatefallback` and `link.textfont` control the fallback text for missing template variables and the label font, falling back to the corresponding trace-level attributes when unset; the label value is formatted with the trace-level `valueformat`/`valuesuffix`
27 changes: 26 additions & 1 deletion src/traces/sankey/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ var baseAttrs = require('../../plots/attributes');
var colorAttrs = require('../../components/color/attributes');
var fxAttrs = require('../../components/fx/attributes');
var domainAttrs = require('../../plots/domain').attributes;
const { hovertemplateAttrs, templatefallbackAttrs } = require('../../plots/template_attributes');
const { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require('../../plots/template_attributes');
var colorAttributes = require('../../components/colorscale/attributes');
var templatedArray = require('../../plot_api/plot_template').templatedArray;
var descriptionOnlyNumbers = require('../../plots/cartesian/axis_format_attributes').descriptionOnlyNumbers;
Expand Down Expand Up @@ -220,6 +220,31 @@ var attrs = (module.exports = overrideAll(
dflt: [],
description: 'The shown name of the link.'
},
textinfo: {
valType: 'flaglist',
flags: ['label', 'value'],
extras: ['none'],
dflt: 'none',
description: [
'Determines which trace information appears permanently on the links.',
'Any combination of *label* and *value* joined with a *+* OR *none*.'
].join(' ')
},
texttemplate: texttemplateAttrs({editType: 'calc'}, {
description: [
'*%{label}: %{valueLabel}* renders the link label and its formatted',
'value; `valueLabel` is the value formatted with `valueformat`/`valuesuffix`.',
'When set per link, an empty entry makes that link fall back to `textinfo`',
'rather than leaving it unlabeled; to label only some of the links,',
'set `textinfo` to *none* and give a template to those links alone.'
].join(' '),
keys: ['label', 'value', 'valueLabel', 'source', 'target', 'customdata', 'meta']
}),
texttemplatefallback: templatefallbackAttrs(),
textfont: fontAttrs({
autoShadowDflt: true,
description: 'Sets the font for the permanent link labels.'
}),
color: {
valType: 'color',
arrayOk: true,
Expand Down
2 changes: 2 additions & 0 deletions src/traces/sankey/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export const cn = {
sankey: 'sankey',
sankeyLinks: 'sankey-links',
sankeyLink: 'sankey-link',
sankeyLinkLabelSet: 'sankey-link-label-set',
sankeyLinkLabel: 'sankey-link-label',
sankeyNodeSet: 'sankey-node-set',
sankeyNode: 'sankey-node',
nodeRect: 'node-rect',
Expand Down
7 changes: 7 additions & 0 deletions src/traces/sankey/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,13 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout

Lib.coerceFont(coerce, 'textfont', layout.font, { autoShadowDflt: true });

const linkTextInfo = coerceLink('textinfo');
const linkTextTemplate = coerceLink('texttemplate');
if(linkTextInfo !== 'none' || linkTextTemplate) {
Lib.coerceFont(coerceLink, 'textfont', traceOut.textfont, { autoShadowDflt: true });
if(linkTextTemplate) coerceLink('texttemplatefallback');
}

// Ensure _length is defined
traceOut._length = null;
};
Expand Down
179 changes: 163 additions & 16 deletions src/traces/sankey/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,17 @@ function linkModel(d, l, i) {
};
}

// The link paths and their permanent labels are two joins over the same links,
// so the models are built once per draw and shared between both selections.
function linkModels(d) {
if(!d._linkModels) {
d._linkModels = d.graph.links
.filter((l) => l.value)
.map((l, i) => linkModel(d, l, i));
}
return d._linkModels;
}

function createCircularClosedPathString(link, arrowLen) {
// Using coordinates computed by d3-sankey-circular
var pathString = '';
Expand Down Expand Up @@ -560,6 +571,96 @@ function linkPath() {
return path;
}

// Builds the permanent-label string for a link from textinfo / texttemplate.
// Returns null when the feature is opted out, so that traces which do not use it
// do no per-link work at all.
function linkTextGetter(gd, trace) {
const linkAttr = trace.link;
const textinfo = linkAttr.textinfo;
const texttemplate = linkAttr.texttemplate;
const flags = (textinfo && textinfo !== 'none') ? textinfo.split('+') : [];
const hasTemplate = Array.isArray(texttemplate) ? texttemplate.length > 0 : !!texttemplate;
if(!flags.length && !hasTemplate) return null;

// the formatter depends on the trace only, so build it once per draw
const formatValue = Lib.numberFormat(trace.valueformat);
const vSuf = trace.valuesuffix;
const locale = gd._fullLayout._d3locale;

return (l, i) => {
const valueLabel = `${formatValue(l.value)}${vSuf}`;

const tt = Array.isArray(texttemplate) ? texttemplate[i] : texttemplate;
if(tt) {
return Lib.texttemplateString({
template: tt,
labels: {valueLabel: valueLabel},
data: [{
label: l.label,
value: l.value,
valueLabel: valueLabel,
source: l.source,
target: l.target,
customdata: l.customdata
}, trace._meta],
locale: locale,
fallback: linkAttr.texttemplatefallback
});
}

if(!flags.length) return '';
const parts = [];
if(flags.indexOf('label') !== -1 && l.label) parts.push(l.label);
if(flags.indexOf('value') !== -1) parts.push(valueLabel);
return parts.join('<br>');
};
}

// Counter-transform that cancels the group matrix applied in sankeyTransform, so
// the label glyphs always read left-to-right and upright. For every combination
// the product (group matrix x this) is the identity:
// h + forward : matrix( 1 0 0 1) -> ''
// h + reversed: matrix(-1 0 0 1) -> scale(-1,1)
// v + forward : matrix( 0 1 1 0) -> scale(-1,1) rotate(90)
// v + reversed: matrix( 0 -1 1 0) -> rotate(90)
// Shared by the node labels and the permanent link labels.
function uprightTransform(d) {
if(d.horizontal) return d.reversed ? 'scale(-1,1)' : '';
return d.reversed ? strRotate(90) : `scale(-1,1)${strRotate(90)}`;
}

// Positions a permanent link label at the link midpoint (layout frame) and keeps
// the glyphs upright. The midpoint stays in the layout frame: the enclosing
// `.sankey` group already carries the orientation/direction transform, so the
// coordinates themselves must not be mirrored here. The trailing translate runs
// in the already uprighted frame and is therefore a plain screen-space shift: it
// centres the whole text block on the anchor instead of its first baseline,
// using the same block metric as the node labels.
function linkLabelTransform(d) {
const l = d.link;
let midX, midY;
if(l.circular) {
// same anchor as the hover label (see hoverCenterPosition in plot.js)
midX = (l.circularPathData.leftInnerExtent + l.circularPathData.rightInnerExtent) / 2;
midY = l.circularPathData.verticalFullExtent;
} else {
// Anchor at the middle of the arrow body: when arrows are shown, the
// head occupies the end of the link at the target side, so it is
// excluded from the span. The clamping matches linkPath() exactly
// (arrow head capped at half the straight span), so the anchor always
// agrees with the drawn path, including on drag frames where the
// layout moves after the link models were built.
const maxArrowLength = Math.abs((l.target.x0 - l.source.x1) / 2);
const arrowLen = Math.min(d.linkArrowLength, maxArrowLength);
midX = (l.source.x1 + l.target.x0 - arrowLen) / 2;
midY = (l.y0 + l.y1) / 2;
}
const blockShift = l.trace.link.textfont.size *
(CAP_SHIFT - ((d.linkLabelLines || 1) - 1) * LINE_SPACING) / 2;

return `${strTranslate(midX, midY)}${uprightTransform(d.parent)}${strTranslate(0, blockShift)}`;
}

function nodeModel(d, n) {
var zoneThicknessPad = c.nodePadAcross;
var zoneLengthPad = d.nodePad / 2;
Expand Down Expand Up @@ -629,9 +730,11 @@ function updateNodeShapes(sankeyNode) {
sankeyNode.call(updateNodePositions);
}

function updateShapes(sankeyNode, sankeyLink) {
function updateShapes(sankeyNode, sankeyLink, sankeyLinkLabel) {
sankeyNode.call(updateNodeShapes);
sankeyLink.attr('d', linkPath());
// empty selection when the permanent labels are not opted in
sankeyLinkLabel.attr('transform', linkLabelTransform);
}

function sizeNode(rect) {
Expand Down Expand Up @@ -694,7 +797,7 @@ function attachPointerEvents(selection, sankey, eventSet) {
});
}

function attachDragHandler(sankeyNode, sankeyLink, callbacks, gd) {
function attachDragHandler(sankeyNode, sankeyLink, sankeyLinkLabel, callbacks, gd) {
var dragBehavior = d3.behavior.drag()
.origin(function(d) {
return {
Expand Down Expand Up @@ -723,7 +826,7 @@ function attachDragHandler(sankeyNode, sankeyLink, callbacks, gd) {
} else { // make a forceLayout if needed
attachForce(sankeyNode, forceKey, d, gd);
}
startForce(sankeyNode, sankeyLink, d, forceKey, gd);
startForce(sankeyNode, sankeyLink, sankeyLinkLabel, d, forceKey, gd);
}
})

Expand All @@ -749,7 +852,7 @@ function attachDragHandler(sankeyNode, sankeyLink, callbacks, gd) {
saveCurrentDragPosition(d.node);
if(d.arrangement !== 'snap') {
d.sankey.update(d.graph);
updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink);
updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink, sankeyLinkLabel);
}
})

Expand Down Expand Up @@ -785,7 +888,7 @@ function attachForce(sankeyNode, forceKey, d, gd) {
.stop();
}

function startForce(sankeyNode, sankeyLink, d, forceKey, gd) {
function startForce(sankeyNode, sankeyLink, sankeyLinkLabel, d, forceKey, gd) {
window.requestAnimationFrame(function faster() {
var i;
for(i = 0; i < c.forceTicksPerFrame; i++) {
Expand All @@ -796,7 +899,7 @@ function startForce(sankeyNode, sankeyLink, d, forceKey, gd) {
switchToSankeyFormat(nodes);

d.sankey.update(d.graph);
updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink);
updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink, sankeyLinkLabel);

if(d.forceLayouts[forceKey].alpha() > 0) {
window.requestAnimationFrame(faster);
Expand Down Expand Up @@ -969,12 +1072,7 @@ module.exports = function(gd, svg, calcData, layout, callbacks) {
.style('fill', 'none');

var sankeyLink = sankeyLinks.selectAll('.' + c.cn.sankeyLink)
.data(function(d) {
var links = d.graph.links;
return links
.filter(function(l) {return l.value;})
.map(linkModel.bind(null, d));
}, keyFun);
.data(linkModels, keyFun);

sankeyLink
.enter().append('path')
Expand All @@ -1001,6 +1099,56 @@ module.exports = function(gd, svg, calcData, layout, callbacks) {
.style('opacity', 0)
.remove();

// Own group, appended between the links and the nodes: entering link paths
// of a later draw must not end up on top of already rendered labels.
const sankeyLinkLabelSet = sankey.selectAll(`.${c.cn.sankeyLinkLabelSet}`)
.data(repeat, keyFun);

sankeyLinkLabelSet.enter()
.append('g')
.classed(c.cn.sankeyLinkLabelSet, true)
.style('pointer-events', 'none');

const sankeyLinkLabel = sankeyLinkLabelSet.selectAll(`.${c.cn.sankeyLinkLabel}`)
.data((d) => {
const getText = linkTextGetter(gd, d.trace);
if(!getText) return [];
const out = [];
linkModels(d).forEach((m) => {
// pointNumber indexes the input arrays, so it is the one an
// arrayOk texttemplate has to be looked up with
const txt = getText(m.link, m.pointNumber);
if(!txt) return;
m.linkLabelText = txt;
out.push(m);
});
return out;
}, keyFun);

sankeyLinkLabel.enter()
.append('text')
.classed(c.cn.sankeyLinkLabel, true)
.attr('text-anchor', 'middle');

sankeyLinkLabel
.attr('data-notex', 1)
.text((d) => d.linkLabelText)
.each(function(d) {
const e = d3.select(this);
Drawing.font(e, d.link.trace.link.textfont);
svgTextUtils.convertToTspans(e, gd);
// cached for linkLabelTransform, which is re-applied on every drag
// frame and must not query the DOM there
d.linkLabelLines = svgTextUtils.lineCount(e);
})
.attr('transform', linkLabelTransform);

sankeyLinkLabel.exit()
.transition()
.ease(c.ease).duration(c.duration)
.style('opacity', 0)
.remove();

var sankeyNodeSet = sankey.selectAll('.' + c.cn.sankeyNodeSet)
.data(repeat, keyFun);

Expand Down Expand Up @@ -1033,7 +1181,7 @@ module.exports = function(gd, svg, calcData, layout, callbacks) {

sankeyNode
.call(attachPointerEvents, sankey, callbacks.nodeEvents)
.call(attachDragHandler, sankeyLink, callbacks, gd); // has to be here as it binds sankeyLink
.call(attachDragHandler, sankeyLink, sankeyLinkLabel, callbacks, gd); // has to be here as it binds sankeyLink

sankeyNode
.transition()
Expand Down Expand Up @@ -1109,8 +1257,7 @@ module.exports = function(gd, svg, calcData, layout, callbacks) {
var posY = d.reversed
? (d.visibleWidth + blockHeight) / 2
: (d.visibleWidth - blockHeight) / 2;
var flipV = d.reversed ? strRotate(90) : ('scale(-1,1)' + strRotate(90));
return strTranslate(posY, pad) + flipV;
return strTranslate(posY, pad) + uprightTransform(d);
}

// horizontal: center along the node length, place just past the thickness edge.
Expand All @@ -1121,7 +1268,7 @@ module.exports = function(gd, svg, calcData, layout, callbacks) {
} else {
posX += d.visibleWidth;
}
return strTranslate(posX, posY) + (d.reversed ? 'scale(-1,1)' : '');
return strTranslate(posX, posY) + uprightTransform(d);
});

nodeLabel
Expand Down
14 changes: 14 additions & 0 deletions src/types/generated/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7014,6 +7014,20 @@ export interface SankeyData {
* @default []
*/
target?: Datum[] | Datum[][] | TypedArray;
/** Sets the font for the permanent link labels. */
textfont?: Font;
/**
* Determines which trace information appears permanently on the links. Any combination of *label* and *value* joined with a *+* OR *none*.
* @default 'none'
*/
textinfo?: 'label' | 'value' | 'none' | (string & {});
/** Template string used for rendering the information text that appears on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `label`, `value`, `valueLabel`, `source`, `target`, `customdata` and `meta`. */
texttemplate?: string | string[];
/**
* Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed.
* @default '-'
*/
texttemplatefallback?: any;
/**
* A numeric value representing the flow volume value.
* @default []
Expand Down
Binary file modified test/image/baselines/sankey_circular.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified test/image/baselines/sankey_circular_reversed.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified test/image/baselines/sankey_circular_vertical.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified test/image/baselines/sankey_circular_vertical_reversed.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified test/image/baselines/sankey_circular_with_arrows.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified test/image/baselines/sankey_circular_with_arrows_reversed.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions test/image/mocks/sankey_circular.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"label": ["0", "1", "2", "3", "4", "5", "6"]
},
"link": {
"textinfo": "value",
"source": [0, 0, 1, 2, 5, 4, 3],
"target": [5, 3, 4, 3, 0, 2, 2],
"value": [1, 2, 1, 1, 1, 1, 1]
Expand Down
1 change: 1 addition & 0 deletions test/image/mocks/sankey_circular_reversed.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"label": ["0", "1", "2", "3", "4", "5", "6"]
},
"link": {
"textinfo": "value",
"source": [0, 0, 1, 2, 5, 4, 3],
"target": [5, 3, 4, 3, 0, 2, 2],
"value": [1, 2, 1, 1, 1, 1, 1]
Expand Down
1 change: 1 addition & 0 deletions test/image/mocks/sankey_circular_vertical.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"label": ["0", "1", "2", "3", "4", "5", "6"]
},
"link": {
"textinfo": "value",
"source": [0, 0, 1, 2, 5, 4, 3],
"target": [5, 3, 4, 3, 0, 2, 2],
"value": [1, 2, 1, 1, 1, 1, 1]
Expand Down
1 change: 1 addition & 0 deletions test/image/mocks/sankey_circular_vertical_reversed.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"label": ["0", "1", "2", "3", "4", "5", "6"]
},
"link": {
"textinfo": "value",
"source": [0, 0, 1, 2, 5, 4, 3],
"target": [5, 3, 4, 3, 0, 2, 2],
"value": [1, 2, 1, 1, 1, 1, 1]
Expand Down
Loading
Loading