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

Roy*_*Roy 5 python candlestick-chart plotly

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

情节的例子。 在约会时添加 V 线。

我想在两个日期之间绘制一条垂直线(例如 11 月 29 日到 11 月 30 日之间 - 上例中 v 线之前的两个烛台)。我怎样才能做到这一点?

ves*_*and 3

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

如果您的日期实际上被格式化为 pandas 日期戳,您可以使用pd.to_pydatetime和此处描述的各种方法轻松找到两个日期之间的日期。由于plotly已经将x轴解释为时间线,因此它将接受数据框中日期之间发生的日期。Plotly 甚至可以处理时间戳,不仅是日期,还包括一天中的时间。

因此,如果您的日期有问题:

datetime.datetime(2020, 10, 11, 0, 0)
Run Code Online (Sandbox Code Playgroud)

和:

datetime.datetime(2020, 10, 12, 0, 0)
Run Code Online (Sandbox Code Playgroud)

那么下面的方法将为您提供:

datetime.datetime(2020, 10, 11, 12, 0)
Run Code Online (Sandbox Code Playgroud)

这将为您提供两个日期之间的一条线,就像您所要求的那样。

看一看:

在此输入图像描述

包含数据和绘图代码的完整片段:

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()
Run Code Online (Sandbox Code Playgroud)