Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set colorscale with reference to dates in plotly python

first question so go easy on me please! I'm trying to create a scatter plot in plotly where the points are coloured according to a datetime column, but it seems to error out. it works fine if I set the color to, say, a numeric column. is there a way to do this please?

Sample code below. if I change color to, say np.arange(0,graph_data.shape[0]) it would work fine but the colorbar labels would be meaningless.

    fig1 = go.Figure()

    fig1.add_trace(go.Scatter(
                        x=graph_data['x_data'],
                        y=graph_data['y_data'],
                        mode='markers',
                        marker={
                            'size': 15,
                            'opacity': 0.95,
                            'line': {'width': 0.5, 'color': 'white'},
                            'color': graph_data['date'],
                            'colorbar': {'title': 'Date'},
                            'colorscale': 'Viridis'
                            }
                        )
like image 555
Rich Haines Avatar asked Aug 31 '25 22:08

Rich Haines


1 Answers

There may be a better way to do this, but one possible workaround is to convert your datetime to seconds after a given date. You could try the following using the datetime module:

int(datetime.datetime.utcnow().timestamp())

This will then be an integer which will be understood by the scatter function.

like image 98
Matt_Haythornthwaite Avatar answered Sep 03 '25 12:09

Matt_Haythornthwaite