如何灵活地显示带有范围分隔符的图形对象散点图(type='line')以不显示排除的范围?

How do I get plotly to display a graph object scatter plot (type='line') with rangebreaks to not display the excluded ranges?

提问人:hk0101 提问时间:11/3/2023 更新时间:11/3/2023 访问量:42

问:

我目前正在尝试使用 plotly 将线图(最终具有多条轨迹)绘制为图形对象。它基于时间序列股票市场价格,由于我只需要/拥有某些日期的数据,因此我需要根据日期或日期时间值排除 xaxis 上不相关的范围。我的数据集可以这样考虑:

d = {'plotPrice': [107, 107.1, 107.2, 106.9, 107, 106.5, 106, 106.2, 106.8, 107], 
     'dateTime': [pd.Timestamp('2023-10-24 08:01:56.668000'), pd.Timestamp('2023-10-24 09:25:58.272'), pd.Timestamp('2023-10-26 11:42:09.199'),
                 pd.Timestamp('2023-10-26 14:54:06.095'),pd.Timestamp('2023-10-26 15:25:50.430'),pd.Timestamp('2023-10-30 09:15:33.546'),
                 pd.Timestamp('2023-10-30 11:34:44.861'),pd.Timestamp('2023-10-30 14:18:27.706'),pd.Timestamp('2023-10-30 15:02:33.771'),
                 pd.Timestamp('2023-10-30 16:30:37.412')]}
df = pd.DataFrame(data=d)

该数据基于即时报价数据,因此没有以相等大小的间隔组织,例如 1 分钟或类似时间间隔,并且由于其他原因,我无法按时间间隔进行聚合。这意味着我需要巧妙地将 xaxis 识别为轴,以便正确缩放它。我当前用于通过 plotly 绘制和应用范围中断的函数如下所示:type=date

def generate_plotly_line_plot(df, titlestr, ccy,saveBool=False):

    # Figure and Layout
    fig = go.Figure()
    fig.update_layout(
        autosize=False,
        width=1000,
        height=500,
        margin=dict(
            l=50,
            r=50,
            b=50,
            t=50,
            pad=4
        ),
        title=go.layout.Title(text=titlestr),
        showlegend=True,
        hovermode='x unified'
    )

    # Format x and y axis
    dateTime_date = df['dateTime'].apply(lambda x: x.date()).unique()
    df_date_range = pd.date_range(df['dateTime'].min(), df['dateTime'].max(), freq='1D').to_series().reset_index(
        drop=True).apply(lambda x: x.date())
    exclude_dates = [x.strftime('%Y-%m-%d') for x in df_date_range if x not in dateTime_date]

    fig.update_xaxes(
        title_text='Date',
        rangebreaks=[
            dict(values=exclude_dates)
        ],
        rangeslider_visible = True
    )

    # Add Traces
    for plot_col in df.columns[df.columns!='dateTime']:
        fig.add_trace(go.Scatter(x=df['dateTime'],
                                 y=df[plot_col],
                                 mode='lines',
                                 name=plot_col,
                                 line=dict(
                                     width=.75
                                 ))
                      )

    fig.update_yaxes(
        title_text="Stock Price in "+ccy)

    fig.show()

generate_plotly_line_plot(df=df[['plotPrice', 'dateTime']],titlestr='Test', ccy='EUR')

上面的脚本将给我以下情节 根据以上示例:在此输入图片描述 根据完整数据:在此输入图片描述

现在的问题是,plotly 似乎实现了范围分隔符,但没有删除 xaxis 上的排除区域,从而导致所需日期之间出现巨大差距。有没有办法使 plotly 正确地从 xaxis 上消除范围间隙?

提前致谢!

我已经尝试了以下方法:

  • 以 或 的形式使用区间突破,但这对我不起作用,因为我需要在正常交易周内排除特定日期。dict(bounds=[16.5, 9], pattern="hour")dict(bounds=["sat", "mon"])
  • 重新格式化 to 字符串,包括小时、分钟、秒和毫秒。 这导致绘图仅显示第一个日期,而不是整个期间。exclude_dates
  • 在每秒/分钟级别上使用,即将更多值作为 传递。 这导致该图也仅显示数据的第一天。exclude_datesexclude_dates
Python 熊猫 时间序列 plotly

评论

0赞 tetris programming 11/3/2023
也许使用 Matplotlib 中断是您正在寻找的:stackoverflow.com/questions/32185411/......
0赞 r-beginners 11/3/2023
这取决于你想检查时间序列的严格程度,但你需要毫秒吗?您还可以通过将 x 轴更改为类别来轻松绘制它。fig.update_xaxes(type='category')
0赞 hk0101 11/3/2023
谢谢你@tetrisprogramming,我也许可以使用剪辑功能或 brokenaxes 包重建它,但当然没有 plotly 的动态功能。@r初学者,我不一定需要毫秒,但使用的问题是,xaxis 刻度将不再正确,即每个刻度/数据点将占用相同的空间量,这意味着在我的示例中,11 月 24 日将占用 xaxis 的 20%,26 日将占用 30%,30 日将占用 xaxis 空间的 50%。谢谢你们俩到目前为止的想法!fig.update_xaxes(type='category')

答: 暂无答案