Search code examples
pythonplotlyplotly-dash

How can I manually color each point in my scatter-plot in plotly?


I have a list of RGB values for each point in my plot, that is not based on a single discrete value nor category, thus built-in methods in plotly express are not working. I tried using go.Figure(), and adding a new trace for each point, however, that is extremely slow. Is there another way of doing this? It seems extremely simple, I'm surprised there's no way to pass color values array to the plotting function.


Solution

  • marker_color can be an array. See below:

    import math
    import plotly.graph_objects as go
    import numpy as np
    
    S = 500
    a = np.random.randint(0, 255, [S, 3]).astype(str)
    a = [f'rgb({",".join(c)})' for c in a]
    
    go.Figure(
        go.Scatter(
            x=np.linspace(0, S/10, S),
            y=np.sin(np.linspace(0, math.pi * S/100, S)),
            mode="markers",
            marker_color=a,
        )
    )
    

    enter image description here