Siddharth Satpathy
Siddharth Satpathy

Reputation: 3043

Same x axis ranges for subplots in Plotly

I am trying to make subplots in Plotly. I have two rows which plot time series data from two different data frames. I want the x axis in the two subplots to be in the sane range. How can I do this?

This is the code that I have for my plotly subplots:

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)

Upvotes: 1

Views: 3368

Answers (1)

vestland
vestland

Reputation: 61104

I'm basing this suggestion on the assumption that you've got two different time-series for two different or over-lapping time indexes. Or else this wouldn't be much of a challenge. I'm going to assume that the time series are of the same length though.

Plot for starting point:

enter image description here

Code for starting point:

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

Plot for suggested solution:

Note that the upper x-axis is hidden using fig['layout']['xaxis']['tickfont']['color']='rgba(0,0,0,0)'

enter image description here

Code for suggested solution:

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

Upvotes: 3

Related Questions