Plotly:如何在烛台图表中的日期之间绘制垂直线?

Plotly: How to draw vertical lines between dates in a candlestick chart?

查看第三个示例 here(在 添加自定义文本和注释 部分)。如果放大图表,您可以看到示例在日期 '2007-12-01' 上插入了一条垂直线。如果日期是一个交易日(例如 '2007-11-29'),人们会看到垂直线正好穿过当天的烛台中间。

我想在两个日期之间画一条垂直线(例如,在 11 月 29 日和 11 月 30 日之间 - 上例中 v 线之前的两个烛台)。我该怎么做?

如果您想查找两个日期之间的日期或时间,您应该考虑在日期上构建您的烛台图表pandas 时间戳。您将在您所指的同一页面的下方 Simple Example with datetime Objects 下找到一个示例。但别担心,您会在这个答案中找到类似方法的完整代码片段。

如果您的日期实际上被格式化为 pandas 日期戳,您可以使用 pd.to_pydatetime and various approaches as described here 轻松找到两个日期之间的日期。由于 plotly 已经将您的 x 轴解释为时间轴,因此它将接受数据框中日期之间发生的日期。 Plotly 甚至会处理时间戳,不仅是日期,还有一天中的时间。

因此,如果您的日期是:

datetime.datetime(2020, 10, 11, 0, 0)

和:

datetime.datetime(2020, 10, 12, 0, 0)

那么下面的方法会给你:

datetime.datetime(2020, 10, 11, 12, 0)

这会给你两个日期之间的界线,就像你要求的那样。

看一看:

包含数据和情节代码的完整片段:

import pandas as pd
import plotly.graph_objects as go
from datetime import datetime

# data
open_data = [33.0, 33.3, 33.5, 33.0, 34.1]
high_data = [33.1, 33.3, 33.6, 33.2, 34.8]
low_data = [32.7, 32.7, 32.8, 32.6, 32.8]
close_data = [33.0, 32.9, 33.3, 33.1, 33.1]
dates = [datetime(year=2020, month=10, day=10),
         datetime(year=2020, month=10, day=11),
         datetime(year=2020, month=10, day=12),
         datetime(year=2020, month=10, day=13),
         datetime(year=2020, month=10, day=14)]


# data organized in a pandas dataframe
df=pd.DataFrame(dict(open=open_data,
                    high=high_data,
                    low=low_data,
                    close=close_data,
                    dates=dates))

# calculations using to_pydatetime() to get the date/time
# between your dates
a=df.dates.iloc[1].to_pydatetime()
b=df.dates.iloc[2].to_pydatetime()
linedate = a + (b - a)/2

# plotly figure setup
fig = go.Figure(data=[go.Candlestick(x=df.dates,
                       open=open_data, high=high_data,
                       low=low_data, close=close_data)])

# edit layouts
fig.update_layout(
    title='Dates are pandas timestamps',
    yaxis_title='AAPL Stock',
    shapes = [dict(
        x0=linedate, x1=linedate, y0=0, y1=1, xref='x', yref='paper',
        line_width=2)],
    annotations=[dict(x=linedate, y=0.8, xref='x', yref='paper',font=dict(
                        color="blue",size=14),
        showarrow=False, xanchor='left', text='Vertical line between two dates')]
)

fig.show()