You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Plotly Express时间序列缺失日期的插值替换为红色高亮范围

解决Plotly Express日期缺失区间的红色高亮问题

当使用Plotly Express绘制带datetime索引的数据时,由于Plotly默认会补全缺失的日期并进行线性插值,connectgaps=False无法直接中断这些自动生成的插值线段。要实现缺失日期区间的红色高亮,可按以下步骤操作:

实现步骤

  • 识别缺失的日期区间:生成完整的日期序列,对比原数据索引,找出所有连续缺失的时间段。
  • 绘制不连接缺失段的折线图:改用Plotly Graph Objects的Scatter绘制折线,关闭自动插值并禁用区间连接。
  • 添加红色高亮形状:在图表中插入红色矩形,标记所有缺失的日期区间。

完整代码实现

import plotly.graph_objects as go
import pandas as pd

def notna_plot(df, relative=False):
    # 计算每行非空值数量(或相对占比)
    if relative:
        data = df.notna().sum(axis=1) / len(df.columns)
    else:
        data = df.notna().sum(axis=1)
    
    # 1. 识别缺失的日期区间
    # 生成完整的日期序列(从数据起始到结束的每日日期)
    full_dates = pd.date_range(start=data.index.min(), end=data.index.max(), freq='D')
    # 找出缺失的日期
    missing_dates = full_dates[~full_dates.isin(data.index)]
    
    # 将连续缺失的日期合并为区间
    gaps = []
    if not missing_dates.empty:
        start_gap = missing_dates[0]
        for i in range(1, len(missing_dates)):
            if (missing_dates[i] - missing_dates[i-1]).days > 1:
                gaps.append((start_gap, missing_dates[i-1]))
                start_gap = missing_dates[i]
        gaps.append((start_gap, missing_dates[-1]))
    
    # 2. 绘制折线图(使用Graph Objects避免自动插值)
    fig = go.Figure()
    fig.add_trace(go.Scatter(
        x=data.index,
        y=data.values,
        mode='lines',
        connectgaps=False,  # 禁用缺失区间的连接
        name='非空值数量' if not relative else '非空值占比'
    ))
    
    # 3. 添加红色高亮区间
    y_min, y_max = data.min(), data.max()
    for start, end in gaps:
        fig.add_shape(
            type='rect',
            x0=start,
            x1=end,
            y0=y_min,
            y1=y_max,
            fillcolor='rgba(255, 0, 0, 0.2)',  # 半透明红色
            line_width=0,
            layer='below'  # 放在折线下方,不遮挡线条
        )
    
    # 设置图表布局
    fig.update_layout(
        xaxis_title='日期',
        yaxis_title='非空值数量' if not relative else '非空值占比',
        title='每行非空值统计(缺失区间红色高亮)'
    )
    
    return fig

代码说明

  • 缺失区间识别:通过生成完整日期序列与原数据索引对比,将连续缺失的日期合并为起止区间,避免重复添加大量单个日期的高亮。
  • 折线绘制:使用go.Scatter而非px.line,直接使用数据中的datetime作为x轴,配合connectgaps=False彻底中断缺失区间的连接线段。
  • 红色高亮:用半透明红色矩形标记缺失区间,设置layer='below'确保高亮不会遮挡折线。

内容的提问来源于stack exchange,提问作者IIU60

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:15:25