Plotly: How to plot markers with time values on a different trace?(Plotly:如何在不同的轨迹上绘制带有时间值的标记?)
问题描述
我有 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
我该怎么做?
推荐答案
您可以分三步完成:
- 使用
go.Figure()
设置图形, - 使用
fig.update(go.Scatter)
为您的 bid_prices 添加跟踪 - 为您的标志做同样的事情.
下面的代码段完全符合您在问题中所描述的内容.我已经设置了两个数据框 df1
和 df2
,然后我将它们合并在一起,以便以后更容易参考.我还显示了累积系列的标志,其中系列中的每个 增量 >0.9
在 flags = [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()
这篇关于Plotly:如何在不同的轨迹上绘制带有时间值的标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Plotly:如何在不同的轨迹上绘制带有时间值的标记?
基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01