moccar
January 29, 2025, 9:31pm
1
I’m working with Plotly’s Sankey diagrams in Python and I would like to display the values on the links permanently, not just when hovering. I’ve looked through the documentation and source code but couldn’t find a property to achieve this.
Current behavior:
Values only show when hovering over links
I’ve tried:
I know it’s a different site, but on sankeyart , it’s displayed nicely and allow easy toggle on-off (which should be doable with dash)
Is there a way to achieve this in Plotly?
EDIT:
So, I looked at the plotly.js github issues, and it seems like there has been this issue open for a couple of years: add optional text on Sankey links · Issue #4746 · plotly/plotly.js · GitHub
I guess it’s not possible…
Use this js code to add link values permanently, I tested it in my R program, it works excellent.
htmlwidgets::onRender(x=p, jsCode=’
function(el) {
//reference code: https://stackoverflow.com/questions/67291003/add-text-to-svg-path-dynamically
//reference code: https://stackoverflow.com/questions/9281199/adding-text-to-svg-document-in-javascript
//reference code: https://stackoverflow.com/questions/52335837/event-when-clicking-a-name-in-the-legend-of-a-plotlys-graph-in-r-shiny
//reference code: https://stackoverflow.com/questions/42280913/troubleshoot-javascript-code-in-onrender-function-of-htmlwidgets
function addLabelText(bgPath, labelText) {
let bbox = bgPath.getBBox();
let x = bbox.x + bbox.width / 2;
let y = bbox.y + bbox.height / 2;
let textElem = document.createElementNS("http://www.w3.org/2000/svg", "text");
textElem.setAttribute("x", x);
textElem.setAttribute("y", y);
textElem.setAttribute("text-anchor", "middle");
textElem.setAttribute("font-size", "10px");
textElem.setAttribute("fill", "black");
textElem.textContent = labelText;
bgPath.parentNode.appendChild(textElem);
console.log(bgPath.parentNode)
}
let myGraph = document.getElementById(el.id);
let nodes = document.querySelectorAll("g.sankey-node");
let links = document.querySelectorAll(".sankey-link");
console.log(myGraph)
console.log(nodes[1])
console.log(links[1])
for (let i = 0; i < links.length; i++) {
addLabelText(links[i], links[i].__data__.link.value)
}
}')