Colorscale in bar chart?

how do we apply a colorscale to a bar chart? I’ve tried witht he ‘colorway’ and ‘colorscale’ parameters but no matter what i do it still applies the default colors?
I’d like to use ‘viridis’ on a bar chart to achieve something like this:

I’ve gone thoruhg the docs here but unfortunately no bar chart so not sure if possible?

thank you

2 Likes

You have to pass the colorscale argument as part of the marker parameter dictionary, and the color argument to take the y values like this:

import plotly.graph_objs as go
x = ['Albania', 'Denmark', 'France', 'Finland', 'USSR']
y = [4, 2, 3, 5, 9]
fig = go.FigureWidget(data=[go.Bar(x=x, y=y,
                                 marker={'color': y,
                                               'colorscale': 'Viridis'})]) 
fig

This chart has one trace, and does not show a legend. If you want to show the legend, you can make each bar a different trace, by passing a list of go.Bars.
(I might be doing something wrong, but the scolorscale here is not taking Viridis and using the default scale.)

import plotly.graph_objs as go
fig2 = go.FigureWidget(data=[go.Bar(x=[x], 
                                   y=[y],
                                   name=x,
                                   marker={'color': y, 
                                           'colorscale': 'Viridis'})
                           for x, y in zip(x, y)]) 
fig2

Hope that helps!

4 Likes

The second example does not look like Viridis to me.

2 Likes

Is there any answer to this?
In my case, it messes everything up and the legend shows just black color, which indicates that the legend elements are not connected to the colors used in the plot.

Thanks in advance for your help!

1 Like

I too am struggling with this.

    scale = px.colors.sequential.BuGn
    fig = px.bar(df, x=loss_col, y=feature_col, orientation='h', color=loss_col)
    fig.update_traces(marker=dict(colorscale=scale))
    fig.show()


This is not my beautiful wife