Search code examples
pythoncolorsplotlyplotly-python

Plotly - color cycle setting from a colormap


For matplotlib, I used this code to change a default color cycle setting, so that I could plot multiple lines with colors in this cycle.


n = 24
color = plt.cm.viridis(np.linspace(0, 1,n))
mpl.rcParams['axes.prop_cycle'] = cycler.cycler('color', color) 

for i in range(30):
    plt.plot(x,y,data[data["col1"]==i]) 
plt.show()

How can I do this for plotly as well?

fig = px.line(data[data["col1"]==i],x,y)

for i in range(30):
    fig.add_scatter(x,y,data[data["col1"]==i],mode="line") 

Solution

  • I often use from itertools import cycle and next(<list of colors>) where <list of colors> could be any sequence of colors, like px.colors.qualitative.Alphabet.

    Here's a setup that comes close to what you're looking for:

    fig = go.Figure()
    for i in range(lines):
        color =  next(col_cycle)
        fig.add_scatter(x = np.arange(0,rows),
                        y = np.random.randint(-5, 6, size=rows).cumsum(),
                        mode="lines",
                        line_color = color,
                        name = color
                       ) 
    

    Plot

    enter image description here

    Complete code:

    from itertools import cycle
    import numpy as np
    col_cycle = cycle(px.colors.qualitative.Alphabet)
    
    rows = 10
    lines = 30
    
    fig = go.Figure()
    for i in range(lines):
        color =  next(col_cycle)
        fig.add_scatter(x = np.arange(0,rows),
                        y = np.random.randint(-5, 6, size=rows).cumsum(),
                        mode="lines",
                        line_color = color,
                        name = color
                       ) 
    fig.show()