Search code examples
pythonplotlyslidersubplotshared

plotting subplots with a shared slider in python


I am trying to plot 3 subplots (separate scatter plots directly one under the other with a separate slider underneath them that controls them all) that share the same x range data with a slider that controls all of them on the bottom. I have managed to do that with one plot but I do not know how to add the other 2 subplots. I am sharing the code with a small part of the dataseries.

from plotly.subplots import make_subplots
import plotly.express as px
import plotly.graph_objects as go
x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # pandas series, string
y1=[90, 92, 89, 82, 82, 78, 76, 82, 85, 88] # pandas series, numpy int64
y2=[20, 21, 19, 20, 18, 17, 14, 16, 18, 23] # pandas series, numpy int64
y3=[40, 42, 41, 42, 44, 45, 47, 49, 45, 46] # pandas series, numpy int64


fig1 = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.1)
fig2 = px.scatter(x=x,y=y1,labels = dict(x = "time",y = "var"))
fig1 = go.Figure(data = fig2.data) # this is defined like that so I can add a second dataset on the same plot if needed, but I need y2,y3 on a separate plot
fig1.update_layout(yaxis_title='var',xaxis_title='time')
fig1.update_xaxes(rangeslider_visible=True)
fig1.show()

Thank you!


Solution

  • To create 3 separate subplots (one above the other) that share the same x range data with a slider that controls all of them, what we can do is we can created 3 traces (one for each subplot) and added them to the subplots with the appropriate row and column values. The rangeslider_visible=True option is set to enable the range slider for the x-axis, which will control all 3 subplots. I hope This Helps.

    from plotly.subplots import make_subplots
    import plotly.graph_objects as go
    
    x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    y1 = [90, 92, 89, 82, 82, 78, 76, 82, 85, 88]
    y2 = [20, 21, 19, 20, 18, 17, 14, 16, 18, 23]
    y3 = [40, 42, 41, 42, 44, 45, 47, 49, 45, 46]
    
    #Adding the traces for each subplot
    fig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.1)
    trace1 = go.Scatter(x=x, y=y1, mode='lines', name='Trace 1')
    trace2 = go.Scatter(x=x, y=y2, mode='lines', name='Trace 2')
    trace3 = go.Scatter(x=x, y=y3, mode='lines', name='Trace 3')
    
    #Add the traces to the subplots
    fig.add_trace(trace1, row=1, col=1)
    fig.add_trace(trace2, row=2, col=1)
    fig.add_trace(trace3, row=3, col=1)
    
    #Setting titles and labels
    fig.update_xaxes(title_text='Time', row=3, col=1)
    fig.update_yaxes(title_text='Var', row=2, col=1)
    
    fig.update_xaxes(rangeslider_visible=True) #Added a range slider to control all subplots
    fig.show() #Showing the Figure