Plotly:如何设置 plotly figure 的样式,使其不显示缺失日期的间隙?

Plotly: How to style a plotly figure so that it doesn't display gaps for missing dates?

我有一个 EUR/JPY 几个月的汇率以 15 分钟为间隔的图表,因此,没有周五晚上到周日晚上的数据。

这是部分数据,请注意周末索引(类型:DatetimeIndex)中的跳过:

在 plotly 中绘制此数据会导致缺失日期出现差距使用上面的数据框:

import plotly.graph_objs as go
candlesticks = go.Candlestick(x=data.index, open=data['Open'], high=data['High'],
                   low=data['Low'], close=data['Close'])
fig = go.Figure(layout=cf_layout)
fig.add_trace(trace=candlesticks)
fig.show()

输出:

如您所见,缺少日期的地方存在空白。我在网上找到的一种解决方案是使用以下方法将索引更改为文本:

data.index = data.index.strftime("%d-%m-%Y %H:%M:%S")

并再次绘制它,这确实有效,但也有它自己的问题。 x 轴标签看起来很糟糕:

我想生成一个图表,该图表绘制的图表与第二个图中一样没有间隙,但 x 轴的显示与第一个图表中的一样。或者至少以更简洁和响应更快的格式显示,尽可能接近第一张图。

提前感谢您的帮助!

即使您的数据集中缺少某些日期,也会将您的日期解释为日期值,甚至在您的时间轴上显示缺失的日期。一种解决方案是获取第一个和最后一个日期,构建一个完整的时间线,找出原始数据集中缺少哪些日期,并将这些日期包含在:

fig.update_xaxes(rangebreaks=[dict(values=dt_breaks)])

这会变成这个数字:

进入这个:

完整代码:

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

# sample data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

# remove some dates to build a similar case as in the question
df = df.drop(df.index[75:110])
df = df.drop(df.index[210:250])
df = df.drop(df.index[460:480])

# build complete timepline from start date to end date
dt_all = pd.date_range(start=df['Date'].iloc[0],end=df['Date'].iloc[-1])

# retrieve the dates that ARE in the original datset
dt_obs = [d.strftime("%Y-%m-%d") for d in pd.to_datetime(df['Date'])]

# define dates with missing values
dt_breaks = [d for d in dt_all.strftime("%Y-%m-%d").tolist() if not d in dt_obs]

# make fiuge
fig = go.Figure(data=[go.Candlestick(x=df['Date'],
                open=df['AAPL.Open'], high=df['AAPL.High'],
                low=df['AAPL.Low'], close=df['AAPL.Close'])
                      ])

# hide dates with no values
fig.update_xaxes(rangebreaks=[dict(values=dt_breaks)])

fig.update_layout(yaxis_title='AAPL Stock')

fig.show()

感谢您提供的精彩样本!适用于每日数据,但日内/5 分钟数据范围突破仅在图表上留下一天

    # build complete timepline 
    dt_all = pd.date_range(start=df.index[0],end=df.index[-1], freq="5T")
    # retrieve the dates that ARE in the original datset
    dt_obs = [d.strftime("%Y-%m-%d %H:%M:%S") for d in pd.to_datetime(df.index, format="%Y-%m-%d %H:%M:%S")]
    # define dates with missing values
    dt_breaks = [d for d in dt_all.strftime("%Y-%m-%d %H:%M:%S").tolist() if not d in dt_obs]

以防万一这里有人想消除非交易时段周末的缺口, 如下图,使用rangebreaks就是做法。

    fig = go.Figure(data=[go.Candlestick(x=df['date'], open=df['Open'], high=df['High'], low=df['Low'], close=df['Close'])])
    fig.update_xaxes(
        rangeslider_visible=True,
        rangebreaks=[
            # NOTE: Below values are bound (not single values), ie. hide x to y
            dict(bounds=["sat", "mon"]),  # hide weekends, eg. hide sat to before mon
            dict(bounds=[16, 9.5], pattern="hour"),  # hide hours outside of 9.30am-4pm
            # dict(values=["2020-12-25", "2021-01-01"])  # hide holidays (Christmas and New Year's, etc)
        ]
    )
    fig.update_layout(
        title='Stock Analysis',
        yaxis_title=f'{symbol} Stock'
    )

    fig.show()

这里是Plotly's doc

要解决日内数据问题,您可以使用 rangebreak 的 dvalue 参数和正确的 ms 值。 例如,1 小时 = 3.6e6 毫秒,因此使用带有此值的 dvalue。

文档在这里:https://plotly.com/python/reference/layout/xaxis/

fig.update_xaxes(rangebreaks=[dict(values=dt_breaks, dvalue=3.6e6)])