Hi guys, I’ve been trying to create a Sankey diagram with Gradient transitions (from left to right) using plotly.graph_objects, but I couldn’t. The initial color for the arrow should be the same for the origin node and then it should gradually transition to the destine node’s color.
My desired chart would be something like the ones provided by Flourish studio:
My actual code follows:
import plotly.graph_objects as go
# Colors for the nodes
node_colors = ["#FFD700", "#ADD8E6", "#FF69B4", "#98FB98", "#9370DB"]
# Function to generate colors with opacity for smooth transitions
def create_opacity_color(base_color, opacity=0.5):
return f"rgba({int(base_color[1:3], 16)}, {int(base_color[3:5], 16)}, {int(base_color[5:7], 16)}, {opacity})"
# Customize this based on your nodes and labels
nodes = ["Love Island", "The Bachelor", "Married At First Sight",
"Still together", "Separated", "No match"]
# Create node indices and apply base colors to them
node_indices = {label: idx for idx, label in enumerate(nodes)}
# Assign node colors based on your scheme
source_node_colors = [create_opacity_color("#ADD8E6"), create_opacity_color("#FFD700"), create_opacity_color("#FF69B4")]
target_node_colors = [create_opacity_color("#98FB98"), create_opacity_color("#9370DB"), create_opacity_color("#FF69B4")]
# Set up sources, targets, and values based on your dataset
source = [0, 0, 0, 1, 1, 1, 2, 2, 2] # Indices of sources
target = [3, 4, 5, 3, 4, 5, 3, 4, 5] # Indices of targets
values = [50, 141, 1055, 50, 141, 1055, 50, 141, 1055] # Corresponding values
# Link colors with gradients (simulate smooth transitions)
link_colors = [
"rgba(173,216,230,0.8)", "rgba(173,216,230,0.6)", "rgba(173,216,230,0.4)", # Light Blue to Greenish gradient
"rgba(255,215,0,0.8)", "rgba(255,215,0,0.6)", "rgba(255,215,0,0.4)", # Yellow to Purple gradient
"rgba(255,105,180,0.8)", "rgba(255,105,180,0.6)", "rgba(255,105,180,0.4)" # Pink to Pinkish gradient
]
# Create the Sankey diagram
fig = go.Figure(go.Sankey(
node=dict(
pad=20,
thickness=30,
line=dict(color="black", width=0.5),
label=nodes,
color=node_colors
),
link=dict(
source=source,
target=target,
value=values,
color=link_colors
)
))
# Update layout for a similar look
fig.update_layout(
title_text="Smooth Transition Sankey Diagram",
font_size=12,
height=600
)
# Show the plot
fig.show()
The generated image is below.