How to limit update_layout margins only to one subplot in Plotly / Dash?

Viewed 619

In a 2 row, 1 column layout, the main plot is positioned above sub.

    fig.add_trace(go.Scatter(x=df.index, y=main_data, name='main',
                             line=dict(color='white', width=1), row=1, col=1)

    fig.add_trace(go.Bar(x=df.index, y=sub_data, name='sub', row=2, col=1)

When I use update_layout as follows:

    fig.update_layout(height=400, margin=dict(t=30, b=15, l=15), pad=20)

the padding is applied to both main and sub.

Is there a way to have padding apply only to main?

1 Answers

fig.update_layout() applies only to the attributes of the entire figure, and that's why you can't address attributes of subplots with fig.update_layout(row = 2, col = 2) like you can with fig.update_traces(row, col). So depending on what you'd like to achieve here, you're going to have to adjust the appearance of your subplots through specs and / or row_heights and column_widths in your make_subplots() call.

Here's an example using both approaches:

enter image description here

Complete code:

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

fig = make_subplots(
    rows=5, cols=2,
    column_widths = [0.7, 0.3],
    row_heights = [0.2, 0.2, 0.2, 0.1, 0.1],
    specs=[[{}, {"rowspan": 2}],
           [{}, None],
           [{"rowspan": 2, "colspan": 2}, None],
           [None, None],
           [{}, {}]],
#     print_grid=True
)

fig.add_trace(go.Scatter(x=[1, 2], y=[1, 2], name="(1,1)"), row=1, col=1)
fig.add_trace(go.Scatter(x=[1, 2], y=[1, 2], name="(1,2)"), row=1, col=2)
fig.add_trace(go.Scatter(x=[1, 2], y=[1, 2], name="(2,1)"), row=2, col=1)
fig.add_trace(go.Scatter(x=[1, 2], y=[1, 2], name="(3,1)"), row=3, col=1)
fig.add_trace(go.Scatter(x=[1, 2], y=[1, 2], name="(5,1)"), row=5, col=1)
fig.add_trace(go.Scatter(x=[1, 2], y=[1, 2], name="(5,2)"), row=5, col=2)

fig.update_layout(height=600, width=600, title_text="specs examples")
fig.show()
Related