Adding opacity to a css color in a Sankey Plot

Is it possible to add an opacity to a color if you’re using a css color? Tried doing this

            self.fig = go.Figure(data=[go.Sankey(
                node=dict(
                    pad=15,
                    thickness=20,
                    line=dict(color="black", width=0.5),
                    label=self.label,
                    color=self.colors['node']
                ),
                link=dict(
                    source=self.source,  
                    target=self.target,
                    value=self.value,
                    color=[[color, .7] for color in self.colors['link']] # self.colors is a list of css colors
                ))])

but it doesn’t work and there’s no way to set an opacity flag. Any help would be appreicated.

Hi, and welcome to the community forum!

In order to modify the opacity of the color of a link in a Sankey figure, you need to pass a list of rgba colors to the figure’s link.color attribute, as demonstrated in the example at https://plotly.com/python/sankey-diagram/#more-complex-sankey-diagram-with-colored-links.

It looks like you’re on the right track but the list comprehension you perform ([color, .7] for color in self.colors['link']) does not result in a list that is in the format that the plotly.py API expects.

If you can share the result of the list comprehension it would be helpful in further debugging your issue.

Hope that helps!

Output looks like this:

[['seagreen', 0.7], ['darkgrey', 0.7], ['steelblue', 0.7], ['navy', 0.7], ['darkturquoise', 0.7]]

Is there an easy way to translate the css color to rgba?

To translate css color names to rgba programmatically, you can use the matplotlib.colors module, which has a function called to_rgba() which accepts a named color and returns an rgba value.

This is documented at https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.colors.to_rgba.html.

1 Like

This is an excellent solution for me as I was reading in a hex code from a custom template and wanted to apply opacity.

I created a global variable for the script which stored a computed f-string of the rgba value of the hex code, and then referenced that variable for the traces which required it.

from matplotlib import colors

PROJECTION_SHADING = f'rgba{colors.to_rgba(my_template.layout.colorway[0], alpha=0.2)}'

fig.add_trace(
    go.Scatter(
        name='High projection',
        x=df['date'],
        y=df['h_projection'],
        marker_color="#444",
        line_width=0,
        mode='lines',
        fillcolor=PROJECTION_SHADING,
        fill='tonexty',
        hovertemplate="%{y}<extra></extra>",
        ),
)

Worked like a charm and avoided the need for a hard coding workaround. Thanks for the suggestion!