Plotly:如何在不同的轨迹上绘制带有时间值的标记?

Plotly: How to plot markers with time values on a different trace?

我有2个数据框: df1 包含列:“时间”、“bid_price” df2 包含列:“time”、“flag”

我想将 df1 的时间序列绘制为折线图,并且我想在 df2“标志”列值 = True 的那些时间点处在该轨迹上放置标记

我该怎么做?

您可以分三步完成:

  1. 使用go.Figure()
  2. 设置图形
  3. 使用 fig.update(go.Scatter)
  4. 为您的 bid_prices 添加跟踪
  5. 对你的旗帜做同样的事情。

下面的代码片段完全符合您在问题中描述的内容。我设置了两个数据框 df1df2,然后将它们合并在一起,以便以后参考。 我还显示了累积系列的标志,其中每个 increment in the series > 0.9 都在 flags = [True if elem > 0.9 else False for elem in bid_price] 中标记。您应该能够轻松地将其调整为您的真实世界数据集的样子。

剧情:

带有随机数据的完整代码:

# 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()