✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

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(
        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)
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)

It would be nice if plotly sankey also had a “textinfo” property like the sunburst plots where you can define what you want appearing on the plot in a single line!

Adding values and percentages to hover is a workaround that might not always be helpful, especially for static plots.

1 Like