How to move a boxplot inside a Figure?

so, i have something like this


this displacement seems unaesthetic. How to move both figures in direction of the center, above their names?
code:

monthly_charges_trace = go.Box(y=df['MonthlyCharges'], name='Monthly Charges',)
total_charges_trace = go.Box(y=df['TotalCharges'], name='Total Charges', yaxis='y2')
data = [monthly_charges_trace, total_charges_trace]
charges_layout = go.Layout(
    yaxis=go.layout.YAxis(
        range = [0, df[['MonthlyCharges']].max() + 40],
        zeroline=False,
    ),
    yaxis2=go.layout.YAxis(
        side='right',
        overlaying='y',
        range = [0, df[['TotalCharges']].max() + 40],
        zeroline=False
    ),
    boxmode='group',
    showlegend=False
)

fig = go.Figure(data=data, layout=charges_layout)
fig.show()

hi @christek
welcome to the community.

Do you have the dataframe (df) that you can share with us so we can run the code locally?

yes, Telco Customer Churn | Kaggle
in TotalCharger column there are some blank values, so i removed them before creating box plot with this code:

df['TotalCharges'] = pd.to_numeric(df.TotalCharges, errors='coerce')

df.dropna(inplace=True)

hi @christek
Thanks for sharing the data.
I used the multiple axes section of the docs to build your graph. Would this work for you?

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


df = pd.read_csv('data.csv')
df['TotalCharges'] = pd.to_numeric(df.TotalCharges, errors='coerce')
df.dropna(inplace=True)


# Create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])

# Add traces
fig.add_trace(
    go.Box(y=df['MonthlyCharges'], name='Monthly Charges'),
    secondary_y=False,
)

fig.add_trace(
    go.Box(y=df['TotalCharges'], name='Total Charges'),
    secondary_y=True,
)
fig.show()

1 Like

thank you very much, i tried to implement make_subplots but failed.