如何在 Plotly Python 中向共享 X 轴图添加实时垂直线?

问题描述 投票:0回答:1

我正在使用 Plotly 创建两个时间序列图,并且我想在当前时间向两个图添加一条垂直的红色虚线,同时共享相同的 x 轴。然而,当我使用“fig.add_vline”函数时,它似乎将该线放置在遥远的过去。我怎样才能让它显示当前时间?下面是我的代码的修改版本,其中有两个共享 x 轴的图和一些可供使用的示例数据:

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import datetime

# Sample data
data1 = {
    'Date': pd.date_range(start='2023-09-01', periods=10, freq='D'),
    'Value1': [10, 12, 15, 8, 9, 11, 13, 14, 10, 12]
}

data2 = {
    'Date': pd.date_range(start='2023-09-01', periods=10, freq='D'),
    'Value2': [5, 7, 9, 6, 8, 10, 11, 12, 7, 6]
}

# Create subplots with shared x-axis
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1)

# Add a scatter plot to the first subplot
fig.add_trace(go.Scatter(x=data1['Date'], y=data1['Value1'], mode='lines', name='Value1'), row=1, col=1)

# Add a scatter plot to the second subplot
fig.add_trace(go.Scatter(x=data2['Date'], y=data2['Value2'], mode='lines', name='Value2'), row=2, col=1)

# Get the current time as a numeric timestamp
current_time = datetime.datetime.now().timestamp()

# Add a vertical dashed red line at the current time to both subplots
fig.add_vline(x=current_time, line=dict(color='red', dash='dash'), annotation_text='Current Time', row='all')

# Show the plot
fig.show()

输出:

python datetime plot time plotly
1个回答
0
投票

所发生的情况显示在折线图的最左侧,因为折线图的 x 轴是日期时间值,当前时间值是最小的浮点值。所以解决方案是对齐 x 轴值。您可以简单地更改为垂直周期设置并以当前时间值作为字符串绘制图表,而不是绘制具有浮点值的折线图,然后将其编辑为时间序列的字符串比例。

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import datetime

# Sample data
data1 = {
    'Date': pd.date_range(start='2023-09-01', periods=10, freq='D'),
    'Value1': [10, 12, 15, 8, 9, 11, 13, 14, 10, 12]
}

data2 = {
    'Date': pd.date_range(start='2023-09-01', periods=10, freq='D'),
    'Value2': [5, 7, 9, 6, 8, 10, 11, 12, 7, 6]
}

# Create subplots with shared x-axis
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1)

# Add a scatter plot to the first subplot
fig.add_trace(go.Scatter(x=data1['Date'], y=data1['Value1'], mode='lines', name='Value1'), row=1, col=1)

# Add a scatter plot to the second subplot
fig.add_trace(go.Scatter(x=data2['Date'], y=data2['Value2'], mode='lines', name='Value2'), row=2, col=1)

# Get the current time as a numeric timestamp
current_time = datetime.datetime.now().strftime(format='%Y-%m-%d')

# Add a vertical dashed red line at the current time to both subplots
fig.add_vrect(x0=current_time, x1=current_time, line=dict(color='red', dash='dash'), annotation_text='Current Time', row='all')

# Show the plot
fig.show()

© www.soinside.com 2019 - 2024. All rights reserved.