Black Lives Matter. Please consider donating to Campaign Zero's mission of ending police violence in America.
https://www.joincampaignzero.org

Sankey diagram with percentages

I’ve created a Sankey diagram, which presents alright, but it would be much more useful if it displayed percentages alongside (or instead) the raw values for each flow (e.g. if my base node sums to 100, and each flow’s value is 20, to also present 20% on each flow’s hover).

Is there a way to do that?

Below is my plotting code:

data = dict(
        type='sankey',
        node = dict(
          pad = 20,
          thickness = 20,
          line = dict(
            color = "black",
            width = 0.25
          ),
          label = label_list
        ),
        link = dict(
          source = df['sourceID'],
          target = df['targetID'],
          value = df['count']
        )
      )
    
    layout =  dict(
        title = title,
        font = dict(
          size = 15
        )
    )
       
    fig = dict(data=[data], layout=layout)
    pio.show(fig)
1 Like

Same question actually, I think somehow we should use the “meta” or “customdata” keys in “hovertemplate” but I can’t understand how and there is no example of how to do that.

As of plotly 4.6, sankey links and nodes now have a customdata attribute and we have updated the documentation accordingly

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], # indices correspond to labels, eg A1, A2, A2, B1, ...
      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()