提问人:edge selcuk 提问时间:9/19/2023 更新时间:9/19/2023 访问量:37
如何在 Plotly Python 中将实时垂直线添加到共享的 X 轴图?
How to Add a Real-Time Vertical Line to Shared X-Axis Plot in Plotly Python?
问:
我正在使用 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()
输出:
答:
0赞
r-beginners
9/19/2023
#1
正在发生的情况在折线图的最左侧描述,因为折线图的 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()
评论