Search code examples
pythonplotlyvisualizationsankey-diagram

Plotly Sankey Diagram: How to display the value for each links and node on the link/node without hover?


In the Plotly Sankey diagram, you are able to see the 'value' of a link/node by hovering over it. I want the image to display the values without hovering though.

I've looked through the documentation and see virtually no way of doing this beside replacing the labels themselves with the desired value. That is not a good option, as nothing would then by labeled. Short of making dynamic labels that include both and and value, I'm not sure how to approach this.

Examples below...

Sample Sankey Diagram (source):

import plotly.graph_objects as go

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label = ["A1", "A2", "B1", "B2", "C1", "C2"],
      customdata = ["Long name A1", "Long name A2", "Long name B1", "Long name B2",
                    "Long name C1", "Long name C2"],
      hovertemplate='Node %{customdata} has total value %{value}<extra></extra>',
      color = "blue"
    ),
    link = dict(
      source = [0, 1, 0, 2, 3, 3],
      target = [2, 3, 3, 4, 4, 5],
      value = [8, 4, 2, 8, 4, 2],
      customdata = ["q","r","s","t","u","v"],
      hovertemplate='Link from node %{source.customdata}<br />'+
        'to node%{target.customdata}<br />has value %{value}'+
        '<br />and data %{customdata}<extra></extra>',
  ))])

fig.update_layout(title_text="Basic Sankey Diagram", font_size=10)
fig.show()

Actual Output: Actual Output

Desired Output: Desired Output


Solution

  • The node positions are determined by non-trivial algorithms and I am afraid that Plotly does not make the coordinates explicit, as of now, see Extract X and Y coordinates from Plotly Sankey diagram. I think you can:

    1. Pass locations computed on your own (may be tricky!), and use the locations to anchor custom annotations Plotly: how to write a text over my Sankey diagram columns?
    2. Inject your information into displayable labels (what you described as an alternative), see Add node count to Plotly Sankey diagram