根据条件在时间序列图上绘制垂直线

Plotly plot a vertical line on a time series plot due to conditions

嗨,我有一个数据框,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)

你完美地描述了你想做的事... 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