Search code examples
pythonplotlyplotly-python

plotly: Is there a way to disable the right axis on adding a secondary axis?


When setting a figure's specs to have 'secondary_y'=True, it automatically adds a placeholder for an axis on the right of the figure. Is there any way to make it go away or change the to span of the subplot?

In the following example see the differences in the right margin of the plot.

enter image description here

For an easy reproduction:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

make_subplots(specs=[[{'secondary_y': True}]]).add_trace(go.Scatter(
    x=[1, 2, 3],
    y=[4, 5, 6],
    name="yaxis1 data"
))

Thanks!


Solution

  • We can create fig1 and fig2 and look at their layout.

    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    
    fig1 = make_subplots(specs=[[{'secondary_y': True}]]).add_trace(go.Scatter(
        x=[1, 2, 3],
        y=[4, 5, 6],
        name="yaxis1 data"
    ))
    
    fig2 = make_subplots().add_trace(go.Scatter(
        x=[1, 2, 3],
        y=[4, 5, 6],
        name="yaxis1 data"
    ))
    

    When we look at the layout for each fig, the x-axis domain is different between the two:

    >>> fig1.layout['xaxis']['domain']
    (0.0, 0.94)
    >>> fig2.layout['xaxis']['domain']
    (0.0, 1.0)
    

    So we can set fig1 to have the same xaxis domain as fig2:

    fig1.layout['xaxis']['domain'] = (0,1)