Skip to content

d3-sankey-circular with grouping #3426

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 4 commits 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
11 changes: 11 additions & 0 deletions src/traces/sankey/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,17 @@ var attrs = module.exports = overrideAll({
description: 'Sets the font for node labels'
}),

groups: {
valType: 'any',
dflt: [],
role: 'calc',
description: [
'Groups of nodes.',
'Each group is defied by an array with the indices of nodes it contains.',
'Multiple groups can be specified.'
].join(' ')
},

node: {
label: {
valType: 'data_array',
Expand Down
2 changes: 2 additions & 0 deletions src/traces/sankey/calc.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ module.exports = function calc(gd, trace) {

return wrap({
circular: circular,
_groups: result.groups,
_groupLookup: result.groupLookup,
_nodes: result.nodes,
_links: result.links
});
Expand Down
6 changes: 4 additions & 2 deletions src/traces/sankey/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ module.exports = {
forceIterations: 5,
forceTicksPerFrame: 10,
duration: 500,
ease: 'cubic-in-out',
ease: 'quart-in-out',
cn: {
sankey: 'sankey',
sankeyLinks: 'sankey-links',
Expand All @@ -28,6 +28,8 @@ module.exports = {
nodeCentered: 'node-entered',
nodeLabelGuide: 'node-label-guide',
nodeLabel: 'node-label',
nodeLabelTextPath: 'node-label-text-path'
nodeLabelTextPath: 'node-label-text-path',
sankeyColumnSet: 'sankey-column-set',
sankeyColumn: 'sankey-node'
}
};
45 changes: 41 additions & 4 deletions src/traces/sankey/convert-to-d3-sankey.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,31 @@ var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
var isIndex = Lib.isIndex;

module.exports = function(trace) {
var nodeSpec = trace.node;
var linkSpec = trace.link;
var nodeSpec = Lib.extendDeep({}, trace.node);
var linkSpec = Lib.extendDeep({}, trace.link);

var links = [];
var hasLinkColorArray = isArrayOrTypedArray(linkSpec.color);
var linkedNodes = {};

var nodeCount = nodeSpec.label.length;

// Grouping
var groups = trace.groups;
var groupLookup = {};
groups.forEach(function(group, groupIndex) {
// Create a node per group
nodeSpec.label[nodeCount + groupIndex] = 'Grouped ' + groupIndex;

// Build a lookup table to quickly find in which group a node is
if(Array.isArray(group)) {
group.forEach(function(nodeIndex) {
groupLookup[nodeIndex] = nodeCount + groupIndex;
});
}
});

nodeCount = nodeSpec.label.length;

var i;
for(i = 0; i < linkSpec.value.length; i++) {
var val = linkSpec.value[i];
Expand All @@ -31,6 +48,24 @@ module.exports = function(trace) {
continue;
}

// Remove links that are within the group
// if(group.indexOf(source) !== -1 && group.indexOf(target) !== -1) {
if(groupLookup.hasOwnProperty(source) && groupLookup.hasOwnProperty(target)) {
continue;
}

// if link targets a node in the group
// if(group.indexOf(target) !== -1) {
if(groupLookup.hasOwnProperty(target)) {
target = groupLookup[target];
}

// if link originates from a node in the group
// if(group.indexOf(source) !== -1) {
if(groupLookup.hasOwnProperty(source)) {
source = groupLookup[source];
}

source = +source;
target = +target;
linkedNodes[source] = linkedNodes[target] = true;
Expand Down Expand Up @@ -62,7 +97,7 @@ module.exports = function(trace) {
label: l,
color: hasNodeColorArray ? nodeSpec.color[i] : nodeSpec.color
});
} else removedNodes = true;
} else removedNodes = false;
Copy link
Contributor Author

@antoinerg antoinerg Jan 11, 2019

Choose a reason for hiding this comment

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

d3-sankey already does that downstream (ie. removing unlinked nodes) and it's useful to keep the unlinked nodes if you want to render something associated to them. For example, I use it with d3 to render and animate ghost nodes on grouping.

}

// need to re-index links now, since we didn't put all the nodes in
Expand All @@ -74,6 +109,8 @@ module.exports = function(trace) {
}

return {
groups: groups,
groupLookup: groupLookup,
links: links,
nodes: nodes
};
Expand Down
3 changes: 3 additions & 0 deletions src/traces/sankey/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}

// group attribute
coerce('groups');

var hoverlabelDefault = Lib.extendDeep(layout.hoverlabel, traceIn.hoverlabel);

// node attributes
Expand Down
102 changes: 83 additions & 19 deletions src/traces/sankey/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ function sankeyModel(layout, d, traceIndex) {
.sankeyCircular()
.circularLinkGap(2)
.nodeId(function(d) {
return d.index;
return d.pointNumber;
});
} else {
sankey = d3Sankey.sankey();
Expand All @@ -60,12 +60,29 @@ function sankeyModel(layout, d, traceIndex) {
.nodes(nodes)
.links(links);

var graph = sankey();

if(sankey.nodePadding() < nodePad) {
Lib.warn('node.pad was reduced to ', sankey.nodePadding(), ' to fit within the figure.');
}

var graph = sankey();
Object.keys(calcData._groupLookup).forEach(function(nodePointNumber) {
var groupIndex = parseInt(calcData._groupLookup[nodePointNumber]);
var groupingNode = graph.nodes.find(function(node) {
return node.pointNumber === groupIndex;
});
groupingNode.key = groupingNode.key + ',' + nodePointNumber;
graph.nodes.push({
pointNumber: parseInt(nodePointNumber),
x0: groupingNode.x0,
x1: groupingNode.x1,
y0: groupingNode.y0,
y1: groupingNode.y1,
partOfGroup: true,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

partOfGroup === true means that this node is included in another node and is a children. It looks as if it's unliked and was deleted by the d3-sankey* engines.

sourceLinks: [],
targetLinks: []
});
});

return {
circular: circular,
key: traceIndex,
Expand Down Expand Up @@ -97,6 +114,14 @@ function sankeyModel(layout, d, traceIndex) {
};
}

function columnModel(d, n) {
var column = {
key: 'column-' + n.column,
coords: [[ (n.x0 + n.x1) / 2, 0], [ (n.x0 + n.x1) / 2, d.height]]
};
return column;
}

function linkModel(d, l, i) {
var tc = tinycolor(l.color);
var basicKey = l.source.label + '|' + l.target.label;
Expand Down Expand Up @@ -159,8 +184,10 @@ function nodeModel(d, n, i) {
var visibleThickness = n.x1 - n.x0;
var visibleLength = Math.max(0.5, (n.y1 - n.y0));

var basicKey = n.label;
var key = basicKey + '__' + i;
var partOfGroup = false;
if(n.partOfGroup) partOfGroup = n.partOfGroup;

var key = n.key || n.pointNumber;

// for event data
n.trace = d.trace;
Expand All @@ -173,6 +200,7 @@ function nodeModel(d, n, i) {
return {
index: n.pointNumber,
key: key,
partOfGroup: partOfGroup,
traceId: d.key,
node: n,
nodePad: d.nodePad,
Expand Down Expand Up @@ -256,19 +284,19 @@ function attachPointerEvents(selection, sankey, eventSet) {
selection
.on('.basic', null) // remove any preexisting handlers
.on('mouseover.basic', function(d) {
if(!d.interactionState.dragInProgress) {
if(!d.interactionState.dragInProgress && !d.partOfGroup) {
eventSet.hover(this, d, sankey);
d.interactionState.hovered = [this, d];
}
})
.on('mousemove.basic', function(d) {
if(!d.interactionState.dragInProgress) {
if(!d.interactionState.dragInProgress && !d.partOfGroup) {
eventSet.follow(this, d);
d.interactionState.hovered = [this, d];
}
})
.on('mouseout.basic', function(d) {
if(!d.interactionState.dragInProgress) {
if(!d.interactionState.dragInProgress && !d.partOfGroup) {
eventSet.unhover(this, d, sankey);
d.interactionState.hovered = false;
}
Expand All @@ -278,7 +306,7 @@ function attachPointerEvents(selection, sankey, eventSet) {
eventSet.unhover(this, d, sankey);
d.interactionState.hovered = false;
}
if(!d.interactionState.dragInProgress) {
if(!d.interactionState.dragInProgress && !d.partOfGroup) {
eventSet.select(this, d, sankey);
}
});
Expand Down Expand Up @@ -353,7 +381,9 @@ function attachDragHandler(sankeyNode, sankeyLink, callbacks) {
function attachForce(sankeyNode, forceKey, d) {
// Attach force to nodes in the same column (same x coordinate)
switchToForceFormat(d.graph.nodes);
var nodes = d.graph.nodes.filter(function(n) {return n.originalX === d.node.originalX;});
var nodes = d.graph.nodes
.filter(function(n) {return n.originalX === d.node.originalX;})
.filter(function(n) {return !n.partOfGroup;});
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Take the children nodes out of the force simulation

d.forceLayouts[forceKey] = d3Force.forceSimulation(nodes)
.alphaDecay(0)
.force('collide', d3Force.forceCollide()
Expand Down Expand Up @@ -497,9 +527,13 @@ module.exports = function(svg, calcData, layout, callbacks) {
.enter().append('path')
.classed(c.cn.sankeyLink, true)
.attr('d', linkPath())
.call(attachPointerEvents, sankey, callbacks.linkEvents);
.call(attachPointerEvents, sankey, callbacks.linkEvents)
.style('opacity', 0);

sankeyLink
.transition()
.ease(c.ease).duration(c.duration)
.style('opacity', 1)
.style('stroke', function(d) {
if(!d.circular) return salientEnough(d) ? Color.tinyRGB(tinycolor(d.linkLineColor)) : d.tinyColorHue;
return d.tinyColorHue;
Expand All @@ -517,17 +551,43 @@ module.exports = function(svg, calcData, layout, callbacks) {
.style('stroke-width', function(d) {
if(d.circular) return d.link.width;
return salientEnough(d) ? d.linkLineWidth : 1;
});

sankeyLink.transition()
.ease(c.ease).duration(c.duration)
.attr('d', linkPath());
})
.attr('d', linkPath());

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

var sankeyColumnSet = sankey.selectAll('.sankeyColumnSet')
.data(repeat, keyFun);

sankeyColumnSet.enter()
.append('g')
.classed('sankeyColumnSet', true);

var sankeyColumn = sankeyColumnSet.selectAll('.sankeyColumn')
.data(function(d) {
var nodes = d.graph.nodes;
return nodes
.map(columnModel.bind(null, d));
}, keyFun);

sankeyColumn.enter()
.append('g')
.classed('sankeyColumn', true);

sankeyColumn
.append('path')
.attr('d', function(column) {
var d = column.coords;
return 'M' + d[0][0] + ',' + d[0][1] + 'V' + d[1][0] + ',' + d[1][1];
})
.style('stroke-width', function() {return '0px';})
.style('stroke-dasharray', function() { return '1 1';})
.style('stroke', function() {return 'black';})
.style('stroke-opacity', function() { return 0.4;});

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

Expand All @@ -549,22 +609,26 @@ module.exports = function(svg, calcData, layout, callbacks) {
var nodes = d.graph.nodes;
persistOriginalPlace(nodes);
return nodes
.filter(function(n) {return n.value;})
// .filter(function(n) {return n.value;})
.map(nodeModel.bind(null, d));
}, keyFun);

sankeyNode.enter()
.append('g')
// .style('opacity', 0)
.classed(c.cn.sankeyNode, true)
.call(updateNodePositions)
.call(attachPointerEvents, sankey, callbacks.nodeEvents);
.style('opacity', 0)


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

sankeyNode.transition()
.ease(c.ease).duration(c.duration)
.call(updateNodePositions);
.call(updateNodePositions)
.style('opacity', function(n) { return n.partOfGroup ? 0 : 1;});

sankeyNode.exit().transition()
.ease(c.ease).duration(c.duration)
Expand Down
3 changes: 2 additions & 1 deletion test/image/mocks/sankey_circular.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
"data": [
{
"type": "sankey",
"groups": [[]],
"node": {
"pad": 1,
"pad": 10,
"label": ["0", "1", "2", "3", "4", "5", "6"]
},
"link": {
Expand Down
Loading