āœŠšŸæ Black Lives Matter. Please consider donating to Black Girls Code today.
šŸ‡ Announcing Dash VTK for 3d simulation graphics. Check out the March webinar.

Colorscales for Sankey diagram not displaying

Hi all. I would like to apply a colorscale for the links in a Sankey diagram so that the first link is yellow, the very last link is blue, and all links in-between are defined by the colorscale 'YlGnBl'. Here is my code:

import plotly.graph_objects as go  

fig = go.Figure(go.Sankey( 
    arrangement = "snap",
    node = {
        "label": names,
        'pad':10,
        'color':'lightgray'
    },  
    link = {
        "source": sources,
        "target": targets,
        "value": values, 
        'colorscales' : [{'colorscale':'YlGnBu'}] 
    })) 
fig.show()

The Sankey diagram itself shows as intended (and no errors are raised), but all links are displayed in the standard light gray color. What is it that goes wrong? I am using Plotly 4.5.3 with Python 3.7.4.
Thanks for helping.

Hi @anne-agathe, welcome to the forum! Iā€™m not sure I understand how sankey colorscales work to be honest, but the only way I found to change the color of links was to use label attributes for the links, as in the example below

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"],
      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],
      label = ["A","B",] * 3,
      colorscales=[{'label': "A", 'colorscale':'RdBu'}, {'label': "B", 'colorscale':'Greens'}]
  ))])

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

But Iā€™m not sure you should use colorscales here, instead you can define one color per link as follows

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"],
      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],
      color=['red', 'blue', 'red', 'yellow', 'green', 'blue'],
  ))])

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


Hope this helps a little.