Viridis color scale for grouped bar plots in Python plotly

Hi, I am trying to produce a bar chart that is grouped on the x-axis (in my plot: the month) and color-coded for each category inside each group. Similar to this chart:
ggplot2-barplot-numeric-x-axis-data-visualization-2 (taken from http://www.sthda.com/)

It should also show a legend. Since the categories have a natural ordering, I would like to use the Viridis color scale. However, I cannot get it to work!

Here is my code:

y = [1,2,3,4,5,6,7,8,9,10]
x = ['202003','202003','202003','202003','202003','202004','202004','202004','202004','202004']
groups= ['first','second','third','fourth','fith','first','second','third','fourth','fith']

fig = go.Figure(
    [
        go.Bar(
            x=x,
            y=y,
            name=group,
            marker={'color': group,'colorscale': 'Viridis'}
        )
        for group in groups
    ]
)

fig.update_layout(
    xaxis=dict(type="category"),
)

fig.show()

Thank you!

Okay, seems like this simple function that has been implemented in ggplot2 and seaborn years ago is not implemented in plotly. That is pretty much a show stopper for me and I will switch back to ggplot2 again.

This should get you pretty close:


import plotly.express as px

y = [1,2,3,4,5,6,7,8,9,10]
x = ['202003','202003','202003','202003','202003','202004','202004','202004','202004','202004']
groups= ['first','second','third','fourth','fith','first','second','third','fourth','fith']

fig = px.bar(x=x,y=y,color=groups, barmode="group", 
                     color_discrete_sequence=px.colors.sequential.Viridis)
fig.update_xaxes(type="category")

fig.show()

Note that this doesn’t resample the Viridis color scale, but it does assign the first N colors from the scale to the groups, in order. We don’t have anything built-in to resample 5 evenly-spaced colors from Viridis but there are other utility libraries that will do this.

1 Like