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

2022-01-21 00:00:00 python plotly plotly-python

问题描述

我有 2 个数据框:df1 包含列:time"、bid_price"df2 包含列:时间"、标志"

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

我想将 df1 的时间序列绘制为折线图,并且我想在这些时间点上 df2flag"列值 = True 的点上放置标记

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

我该怎么做?


解决方案

您可以分三步完成:

  1. 使用 go.Figure() 设置图形,
  2. 使用 fig.update(go.Scatter)
  3. 为您的 bid_prices 添加跟踪
  4. 为您的标志做同样的事情.

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

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.

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

相关文章