Issue when plotting specific rows in a stock chart

Viewed 25

I'm using pandas to plot a chart of stock data with datetime index in the dataframe. I'd like to plot black markers for rows where df_raw[col_name]!=0 but it is acting funky. When no dataframe rows meet the condition, the plot displays fine.

Can you help me understand what I'm doing wrong? Note that data for this stock is available for several decades, but I'm pulling only last 7 days of 1m data.

Thanks so much!

fig.add_trace(go.Scatter(
    x=df_raw[df_raw[col_name]!=0].index,
    y=[df_raw['Close'][j] for j in df_raw[df_raw[col_name]!=0].index],
    mode='markers',
    marker=dict(
        size=8,
        color='black',
        symbol='cross'
    ),
    name='Cdl Pattern'
))
1 Answers

I may have found the answer and wanted to post it here in case it helps others. Here's the complete plotting code. Notice that it first plots the 'Close', and then the markers.

When plotting 'Close', the system uses row numbers instead of indices, but when plotting the markers, it is explicitly being directed to use indices. Since indices are Datetime, the two plots end up with mismatched x-axis.

fig = go.Figure()
fig.add_trace(go.Scatter(
    ###No x-axis provided, the system uses dataframe row numbers###
    y=validation_df['Close'],
    mode='lines+markers',
    name='Original Plot'
))

fig.add_trace(go.Scatter(
    ###Explicitly using .index on x-axis###
    x=df_raw[df_raw[col_name]!=0].index,
    y=[df_raw['Close'][j] for j in df_raw[df_raw[col_name]!=0].index],
    mode='markers',
    marker=dict(
        size=8,
        color='black',
        symbol='cross'
    ),
    name='Cdl Pattern'
))

To correct this, the x-axis had to be converted to row numbers for which I used pd.Series. Please suggest a better method if you know one.

fig = go.Figure()
fig.add_trace(go.Scatter(
    y=validation_df['Close'],
    mode='lines+markers',
    name='Original Plot'
))

fig.add_trace(go.Scatter(
    ###using pd.Series to get row numbers for x-axis###
    x=pd.Series(df_raw[col_name].to_list())[pd.Series(df_raw[col_name].to_list())!=0].index,

    y=[df_raw['Close'][j] for j in df_raw[df_raw[col_name]!=0].index],
    
    mode='markers',
    marker=dict(
        size=8,
        color='black',
        symbol='cross'
    ),
    name='Cdl Pattern'
))
Related