3
votes

I have 2 data frames: df1 contains columns: “time”, “bid_price” df2 contains columns: “time”, “flag”

I want to plot a time series of df1 as a line graph and i want to put markers on that trace at points where df2 “flag” column value = True at those points in time

How can i do this?

1

1 Answers

2
votes

You can do so in three steps:

  1. set up a figure using go.Figure(),
  2. add a trace for your bid_prices using fig.update(go.Scatter)
  3. and do the same thing for your flags.

The snippet below does exactly what you're describing in your question. I've set up two dataframes df1 and df2, and then I've merged them together to make things a bit easier to reference later on. I'm also showing flags for an accumulated series where each increment in the series > 0.9 is flagged in flags = [True if elem > 0.9 else False for elem in bid_price] . You should be able to easily adjust this to whatever your real world dataset looks like.

Plot:

enter image description here

Complete code with random data:

# imports
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import random

# settings
observations = 100
np.random.seed(5); cols = list('a')
bid_price = np.random.uniform(low=-1, high=1, size=observations).tolist()
flags = [True if elem > 0.9 else False for elem in bid_price]
time = [t for t in pd.date_range('2020', freq='D', periods=observations).format()]


# bid price
df1=pd.DataFrame({'time': time, 
                 'bid_price':bid_price})
df1.set_index('time',inplace = True)
df1.iloc[0]=0; d1f=df1.cumsum()

# flags
df2=pd.DataFrame({'time': time, 
                 'flags':flags})
df2.set_index('time',inplace = True)

df = df1.merge(df2, left_index=True, right_index=True)
df.bid_price = df.bid_price.cumsum()
df['flagged'] = np.where(df['flags']==True, df['bid_price'], np.nan)

# plotly setup
fig = go.Figure()

# trace for bid_prices
fig.add_traces(go.Scatter(x=df.index, y=df['bid_price'], mode = 'lines',
                         name='bid_price'))

# trace for flags
fig.add_traces(go.Scatter(x=df.index, y=df['flagged'], mode = 'markers',
              marker =dict(symbol='triangle-down', size = 16),
              name='Flag'))
               
fig.update_layout(template = 'plotly_dark')

fig.show()