Search code examples
pythonplotlysubplotxticks

Plotly: How to set xticks for all subplots?


I am unable to manipulate the xticks on all of my subplots. The method for xticks that I am using (as per documentation) changes the xticks of only the top-most subplot.

How can I change the xticks for the lower subplot as well?

Below is my code:

fig = make_subplots(rows=2, cols=1)

fig.add_trace(
    go.Scatter(x=np.arange(len(df)), y=df['ro2ofst1 ()'], name='ro2ofst1'),
    row=1, col=1
)

fig.add_trace(
    go.Scatter(x=np.arange(len(df)), y=df['ro2ofst2 ()'], name='ro2ofst2'),
    row=2, col=1
)

fig.update_yaxes(range=[0,300],title='mV',row=1,col=1)
fig.update_yaxes(range=[0,300],title='mV',row=2,col=1)
fig.update_xaxes(title_text='data samples',row=2,col=1)

fig.update_layout(title = 'RO2OFST',
                 xaxis = dict(
                 tickmode = 'linear',
                 tick0=0,
                 dtick=25000))
fig.show()

The fig.update_layout above changes the xticks only for subplot in row 1 column 1, but the bottom subplot retains the default xticks.

Thank you

R


Solution

  • You can access all xaxis in your fig and set the range using a for loop like this:

    myRange=[0,6]
    for ax in fig['layout']:
        if ax[:5]=='xaxis':
            fig['layout'][ax]['range']=myRange
    

    Plot:

    enter image description here

    Complete code:

    from plotly.subplots import make_subplots
    import plotly.graph_objects as go
    
    fig = make_subplots(rows=3, cols=1)
    
    fig.append_trace(go.Scatter(
        x=[3, 4, 5],
        y=[1000, 1100, 1200],
    ), row=1, col=1)
    
    fig.append_trace(go.Scatter(
        x=[2, 3, 4],
        y=[100, 110, 120],
    ), row=2, col=1)
    
    fig.append_trace(go.Scatter(
        x=[0, 1, 2],
        y=[10, 11, 12]
    ), row=3, col=1)
    
    myRange=[0,6]
    for ax in fig['layout']:
        if ax[:5]=='xaxis':
            fig['layout'][ax]['range']=myRange
    
    fig.update_layout(height=600, width=600, title_text="Stacked Subplots")
    fig.show()