pythonplotlyplotly-python

How to apply margin between main Y-Axis Title vs. Subplot Y-Axis Title


I created two heatmap objects that I want to combine them into a single subplot. So far, tracing them and setting them together worked out. However, I cannot add spacing between the make_subplot y_title and the subplot titles present. Looking through the documentation for plotly there are no parameters for placing margins to the top level chart.

Here's the basic idea of the script used to build out the two heatmaps into one subplot:

fig = make_subplots(
    rows=2, 
    cols=1, 
    row_heights=[0.75, 0.25], 
    vertical_spacing = 0.1,
    x_title="Current Transactions",
    y_title="Previous Transactions",
)

# Returning Section
for trace in returning.data:
    fig.add_trace(trace, row=1, col=1)

# NTO Section
for trace in nto.data:
    fig.add_trace(trace, row=2, col=1)

fig.update_xaxes(
    row=1,
    col=1,
    showticklabels=True,
    side="top"
)

# Generate final layout
fig.update_layout(
    title="Financing Mapping",
    height=500, 
    width=600,
    hovermode=False,
    autosize=False,
    # margin=dict(l=200)  # This added margin to the whole thing
)

fig.show()

Plotly plot which contains two heatmap graphs with their respective label. However, the main y_title is intersecting with the y-axis labels of the subplot


Solution

  • Subplot x/y titles are represented by figure annotations, which can be customized. The annotation for the y title typically looks like this :

    {
        'font': {'size': 16},
        'showarrow': False,
        'text': 'Previous Transactions',
        'textangle': -90,
        'x': 0,
        'xanchor': 'right',
        'xref': 'paper',
        'xshift': -40,
        'y': 0.5,
        'yanchor': 'middle',
        'yref': 'paper'
    }
    

    In your situation, you can increase the layout left margin (default is 80px) and tweak the xshift parameter as needed.

    xshift - Shifts the position of the whole annotation and arrow to the right (positive) or left (negative) by this many pixels.

    For example :

    fig.update_layout(margin_l=140)
    fig.update_annotations(selector=dict(text='Previous Transactions'), xshift=-100)
    

    See also Text and Annotations in Python.