Plotly 中子图的 x 轴范围相同

Same x axis ranges for subplots in Plotly

我正在尝试在 Plotly 中制作子图。我有两行绘制来自两个不同数据帧的时间序列数据。我希望两个子图中的 x 轴在正常范围内。我该怎么做?

这是我的情节子图代码:

trace_df1 = go.Scatter(
   y=df1[“y”],
   x=df1[“x”]
)

trace_df2 = go.Scatter(
    y=df2[“y”],
    x=df2[“x”]
)


fig = tools.make_subplots(rows=2, cols=1)
fig.append_trace(trace_df1, 1, 1)
fig.append_trace(trace_df2, 2, 1)

我提出这个建议是基于这样的假设:two different or over-lapping time indexes 有两个不同的时间序列。否则这不会是一个很大的挑战。不过,我将假设时间序列属于 same length

起点图:

起点代码:

# imports
from plotly.subplots import make_subplots
import plotly.graph_objs as go
import pandas as pd
import numpy as np

# data 1
np.random.seed(123)
frame_rows = 40
frame_columns = ['V_1']
df_1 = pd.DataFrame(np.random.uniform(-10,10,size=(frame_rows, len(frame_columns))),
                  index=pd.date_range('1/1/2020', periods=frame_rows),
                    columns=frame_columns)
df_1=df_1.cumsum()+100
df_1.iloc[0]=100
df_1

# data 2
frame_rows = 40
frame_columns = ['V_1']
df_2 = pd.DataFrame(np.random.uniform(-10,11,size=(frame_rows, len(frame_columns))),
                  index=pd.date_range('2/2/2020', periods=frame_rows),
                    columns=frame_columns)
df_2=df_2.cumsum()+100
df_2.iloc[0]=100

# plotly
fig = go.Figure()
fig.add_trace(go.Scatter(x=df_1.index, y=df_1['V_1']))
fig.add_trace(go.Scatter(x=df_2.index, y=df_2['V_1']))
fig.show()

建议解的绘图:

请注意,使用 fig['layout']['xaxis']['tickfont']['color']='rgba(0,0,0,0)'

隐藏了上方的 x 轴

建议解决方案代码:

df_1b = df_1.reset_index()
df_1b

df_2b = df_1.reset_index()
df_2b

# source data, integer as index
fig = make_subplots(rows=2, cols=1)
fig.add_trace(go.Scatter(x=df_1b.index, y=df_1['V_1']), row=1, col=1)
fig.add_trace(go.Scatter(x=df_2b['index'], y=df_2['V_1']), row=2, col=1)
fig['layout']['xaxis']['tickfont']['color']='rgba(0,0,0,0)'
fig.show()