Search code examples
pythoncolorsplotly-python

Plotly - python - How to loop through colors


I have a simple plot. How do I loop through colors in a list of rgb colors?

import plotly.express as px

X1 = [1,2,3]
Y1 = [2,4,8]
Z1 = [3,6,8]

colors = ['rgb(255,0,0)','rgb(255,165,0)','rgb(0,0,255)']


cat = ['A','B','C']


    
figtest = px.scatter_3d(x = X1, y = Y1, z = Z1, color = cat)
figtest.update_traces(marker_color = [x for x in colors])
figtest.show()

What I got: enter image description here


Solution

  • you can create a dictionary of categories and then pass it through the color_discrete_map parameter like so - it'll then look up the color based on the cat value:

    import plotly.express as px
    
    X1 = [1, 2, 3]
    Y1 = [2, 4, 8]
    Z1 = [3, 6, 8]
    cat = ['A', 'B', 'C']
    
    color_map = {'A': 'rgb(255,0,0)', 'B': 'rgb(255,165,0)', 'C': 'rgb(0,0,255)'}
    
    figtest = px.scatter_3d(x=X1, y=Y1, z=Z1, color=cat, color_discrete_map=color_map)
    figtest.show()