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 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)
      title='Sum of ',
      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)])
1 Like

Thanks @r-beginners! This solves my problem.