Search code examples
pythonpandasplotly

Plotly range of subplot doesn't change


I'm trying to set the range of subplots using xaxis_range but I found it's working on the left subplot only

Data

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

data = {'variable': {0: 'Case', 1: 'Exam', 2: 'History', 3: 'MAP', 4: 'Volume'},
 'margins_fluid': {0: 0.497, 1: 0.668, 2: 0.506, 3: 0.489, 4: 0.718},
 'margins_vp': {0: 0.809, 1: 0.893, 2: 0.832, 3: 0.904, 4: 0.92}}

df = pd.DataFrame(data)

Plot

# create subplots
fig = make_subplots(
    rows=1,
    cols=2,
    shared_xaxes=False,
    shared_yaxes=True,
    horizontal_spacing=0,
    subplot_titles=['<b>Fluid</b>', '<b>Vasopressor</b>'])

fig.append_trace(
    go.Bar(
        x=df['margins_fluid'],
        y=df['variable'], 
        text=df["margins_fluid"], 
        textposition='inside',
        texttemplate="%{x:.4p}",
        orientation='h', 
        width=0.7, # space between bars 
        showlegend=False, ), 
        1, 1) # 1,1 represents row 1 column 1 in the plot grid

fig.append_trace(
    go.Bar(
        x=df['margins_vp'],
        y=df['variable'], 
        text=df["margins_vp"],
        textposition='inside',
        texttemplate="%{x:.4p}",
        orientation='h', 
        width=0.7, 
        showlegend=False), 
        1, 2) # 1,2 represents row 1 column 2 in the plot grid

fig.update_xaxes(
    tickformat=',.0%', 
    row=1,
    col=1,
    autorange='reversed',)
fig.update_xaxes(
    tickformat=',.0%', 
    row=1,
    col=2)

fig.update_layout(
    title_text="Title",
    barmode="group",
    width=800, 
    height=700,
    title_x=0.5,
    xaxis_range=[0, 1], # This doesn't work
    xaxis2_range=[0, 1], # This works
)

fig.show()

enter image description here


Solution

  • It looks like when you set autorange='reversed', this disables the xaxis_range argument from working (as described here).

    One possible solution would be to reverse the xaxis_range itself by setting xaxis_range=[1,0].

    fig.update_xaxes(
        tickformat=',.0%', 
        row=1,
        col=1,)
    fig.update_xaxes(
        tickformat=',.0%', 
        row=1,
        col=2)
    
    fig.update_layout(
        title_text="Title",
        barmode="group",
        width=800, 
        height=700,
        title_x=0.5,
        xaxis_range=[1, 0], # This works
        xaxis2_range=[0, 1], # This works
    )
    

    enter image description here