How can I iterate over plotly color scale?

I want to iterate over a plotly color scale so I can create a list of colors to apply to each of my 22 line graphs. I’m plotting this using Streamlit. This is my code below:

import plotly.express as px
import streamlit as st

cmap = px.colors.sequential.Viridis
color_scale = [cmap[i % 256] for i in range(22)]

fig = px.line(df, x='Month', y='Sum', color='group', color_discrete_sequence=color_scale)
fig.update_layout(
      title='Sum of ',
      xaxis_title='Month',
      yaxis_title='Views over time'
   )
st.plotly_chart(fig, use_container_width=True)

I’m getting the error : β€˜[cmap[i % 256] for i in range(22)], IndexError: list index out of range’ when I run the code. I know this means the list cmap has fewer colors/items than 22, but I divided i by a large number to keep the index within bounds and still I get the same error. How can I fix this?

There is an answer to your challenge in the stack overflow, and I think the second answer is the best one.

n_colors = 22
color_scale = px.colors.sample_colorscale("viridis", [n/(n_colors -1) for n in range(n_colors)])
2 Likes

Thanks @r-beginners! This solves my problem.