Home > Enterprise >  Plotly: Indexing and plotting timestamps
Plotly: Indexing and plotting timestamps

Time:07-29

I am creating a plotly graph with a slider. enter image description here In the 2nd line I want to add a marker My issue is in the 2nd line of the code below:

fig.add_trace(go.Scatter(visible=False, x=time_qin, y=q_in_cum_plot, mode='lines', line=dict(color='red')), row=3, col=1)
fig.add_trace(go.Scatter(visible=False, x=time_qin[row], y=q_in_cum_plot[row],  mode='markers', marker=dict(color='red')), row=3, col=1)

time_qin is an array that contains datetime values. When I'm indexing over time_qin in the 2nd line I obtain the following error:

ValueError: 
Invalid value of type 'datetime.date' received for the 'x' property of scatter
    Received value: datetime.date(2020, 5, 12)

The 'x' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series

So when calling time_qin[row] a datetime.date type is received that plotly can not handle. Is there a work around in order to add the tracer to the plot? Many thanks for the help.

CodePudding user response:

The most likely cause of this error is that if the index is a single value, the resulting value is the value itself and not a list, array, or series, so it is occurring. The solution is to specify it in a list format. My code uses stock price data and the index is a single number. I use line or mar mode because it is indistinguishable in line mode for scatter plots.

import yfinance as yf
data = yf.download("AAPL", start="2022-05-01", end="2022-07-01")

import plotly.graph_objects as go

row = 84
fig = go.Figure()
fig.add_trace(go.Scatter(visible=True, x=data.index, y=data['Close'], mode='lines', line=dict(color='red')))
fig.add_trace(go.Scatter(visible=True,
                         x=[data.index[row]],
                         y=[data['Close'][row]],
                         mode='lines markers',
                         line=dict(
                             color='green',
                             width=2
                         )
                        )
             )
fig.update_layout(template='plotly_white')
fig.show

enter image description here

  • Related