John
John

Reputation: 3

Sankey chart in Python

I would very much like to make an illustration like the one in the link:

How to add a label to each stratum to display additional information in a rank-change chart using alluvial in R?

I have trouble doing it in Python as it creates multiple linked figures which I do not want. My script is:

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", "A3", "A4", "A5", "A1", "A2", "A3", "A4", "A5"],
      color = "blue"
    ),
    link = dict(
      source = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], # indices correspond to labels, eg A1, A2, A1, B1, ...
      target = [2, 3, 4, 1, 5, 0, 9, 6, 7, 8],
      value = [8, 4, 2, 8, 4, 2,1, 0, 2, 3]
  ))])

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

Can someone please help me?

Upvotes: 0

Views: 584

Answers (1)

r-beginners
r-beginners

Reputation: 35135

Since you are using the Sankey dialog on the official site, I will edit it to show the data structure between the ABs. Simply put, the source is A, the target is B, and the rest is an iteration of that. The additional labels as shown in the link in your question are not available in plotly's sankey dialog as far as I know. You'll have to get creative with the labels. I will add a text based explanation of what I am doing.

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", "A3", "A4", "A5", "B1", "B2", "B3", "B4", "B5"], 
      color = "blue"
    ),
    link = dict(source = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4],
                target = [5, 6, 8, 9, 7, 8, 6, 7, 9, 5], 
                value =  [8, 4, 3, 2, 6, 3 ,4 ,5, 2, 4] 
  ))])

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

# Data structure
# labels  ->  A1 A2  A3  A4  A5  B1  B2  B3  B4  B5
# positon -> [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

# souce[0], value[0], target[0]
# [position](lables):[0]("A1") -> [8] -> [5]("B1")
# souce[1], value[1], target[1]
# [position](lables):[1]("A2") -> [4] -> [6]("B2")
# souce[2], value[2], target[2]
# [position](lables):[2]("A3") -> [3] -> [8]("B3")
...

enter image description here

Upvotes: 1

Related Questions