图中子图的x轴范围相同

时间:2019-11-07 08:20:05

标签: plotly plotly-python

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

1 个答案:

答案 0 :(得分:1)

我基于一个假设,假设您为two different or over-lapping time indexes有两个不同的时间序列。否则,这将不是什么挑战。我将假设时间序列为same length

起点图:

enter image description here

起点代码:

# 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)'

隐藏的

enter image description here

建议的解决方案代码:

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