首页 > 解决方案 > Plotly 中子图的相同 x 轴范围

问题描述

我正在尝试在 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)

标签: pythonplotlyplotly-python

解决方案


我提出这个建议的前提是你有两个不同的时间序列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()

绘制建议的解决方案:

请注意,上方的 x 轴使用隐藏fig['layout']['xaxis']['tickfont']['color']='rgba(0,0,0,0)'

在此处输入图像描述

建议解决方案的代码:

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()

推荐阅读