在现有图形上添加不带yaxis值的点(标记)

2024-10-03 21:26:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张我的portflio股票在一段时间内的图表,它如下所示:

enter image description here

我有一个每5分钟的价格,所以x数据是时间戳,y数据只是数字

我还有一个带有操作时间的数据框,其中包含操作时间及其类型(购买或出售),如下所示:

enter image description here

我想为我的图形上的每个操作添加一个点或某种标记,但我不知道怎么做,我没有y值。时间戳x值不同于操作x值,所以我不能只从现有图中获取y值。 这是我理想的设想,但对于初学者,我只想了解如何在图表上添加我的点:

enter image description here . 我正在使用plotly,但我不在乎解决方案是否需要matplotlib或其他任何东西


Tags: 数据标记图形类型图表时间价格数字
1条回答
网友
1楼 · 发布于 2024-10-03 21:26:09

这在使用annotations时是完全可行的。操作数据框不必有y值,因为您可以在操作x值处使用股票数据中相应的y值。要打印红色标记,可以打印操作并根据需要设置标记属性

然后,您可以循环操作_df,并根据输入日期及其对应的股票投资组合y值在散点图上放置注释。下面是一个包含一些虚构数据的示例,因此您可能需要针对数据帧调整此代码

import numpy as np
import pandas as pd

import plotly.graph_objs as go

## create some random data
np.random.seed(42)

df = pd.DataFrame(
  data=500*np.random.randint(0,1000,24), 
  columns=['price'], 
  index=pd.date_range(start='12/1/2020', end='12/1/2020 23:00:00', freq='H')
)

operations_df = pd.DataFrame(
  data=['Buy','Sell','Buy'], 
  columns=['Operation_type'], 
  index=pd.to_datetime(['12/1/2020 08:00:00', '12/1/2020 12:00:00', '12/1/2020 16:00:00'])
)

fig = go.Figure(data=[go.Scatter(
  x=df.index,
  y=df.price
  )])

fig.add_trace(go.Scatter(
  x=operations_df.index,
  y=[df.loc[date, 'price'] for date in operations_df.index],
  mode='markers',
  marker=dict(
    size=16,
    color="red")
  ))

for date, row in operations_df.iterrows():
  # print(date, df.loc[date, 'price'], row['Operation_type'])
  fig.add_annotation(
    x=pd.to_datetime(date),
    y=df.loc[date, 'price'],
    xref="x",
    yref="y",
    font=dict(
      size=16,
      color="red"
      ),
    text=row['Operation_type'],
    bordercolor="red",
    width=80,
    height=60,
    arrowcolor="red",
    ax=0,
    ay=-150
    )

fig.update_layout(showlegend=False)

fig.show()

enter image description here

相关问题 更多 >