【问题标题】:Plotly plot a vertical line on a time series plot due to conditions由于条件,在时间序列图上绘制一条垂直线
【发布时间】:2021-04-01 05:00:49
【问题描述】:

您好,我有一个数据框,x 轴上有时间序列,y 轴上有值。 我正在使用 Plotly 并试图在我的 df.Alert == 1 的 x 轴上绘制一条垂直线。 目前我正在使用另一个带有红色标记的叠加层来绘制它,但我希望切换到一条受图表的 y 值限制的垂直线。 y 轴上的值仍应由我的轨迹图而不是垂直线确定。

我有办法做到这一点吗?

我的代码示例写在下面

Trace = go.Scatter(
    name = "Values",
    x = df.DateTime,
    y = df.Values,
    mode='markers',
    text= "Unit: " + df['Unit'].astype(str),
   ) 

Alert = go.Scatter(
    name = "Alert",
    x = df.DateTime,
    y = df.Values.where(df.Alert == 1),
    mode='markers',
    line = dict(color = "red"),
    text= "Unit: " + df['Unit'].astype(str),
   ) 


layout = go.Layout(
    xaxis = dict(title = "Date and Time"),
    yaxis = dict(title = "Values")
)

data = [Trace, Alert]
figure = go.Figure(data = data, layout = layout)    
py.iplot(figure)

【问题讨论】:

    标签: python-3.x pandas dataframe plotly plotly-dash


    【解决方案1】:

    你完美地描述了你想做什么...... plot vline

    • 遍历 DF 中 警报 fig.add_vline() 的行
    n=50
    df = pd.DataFrame({"DateTime":pd.date_range("1-jan-2021", freq="15min", periods=n),
                       "Alert":np.random.choice([0]*10+[1], n),
                       "Unit":np.random.choice([0,1,2,3], n),
                       "Values":np.random.uniform(1,10, n)})
                       
    Trace = go.Scatter(
        name = "Values",
        x = df.DateTime.astype(str),
        y = df.Values,
        mode='markers',
        text= "Unit: " + df['Unit'].astype(str),
       ) 
    
    layout = go.Layout(
        xaxis = dict(title = "Date and Time"),
        yaxis = dict(title = "Values")
    )
    
    data = [Trace]
    figure = go.Figure(data = data, layout = layout)    
    
    
    for r in df.loc[df.Alert.astype(bool),].iterrows():
        figure.add_vline(x=r[1]["DateTime"],  line_width=1, line_dash="solid", line_color="red")
    
    figure
    

    【讨论】: