Search code examples
pythonplotlyvisualizationtoolbar

Autoscaling a figure with heatmap + scatter introduces extra padding


The code below

import numpy as np
import plotly.graph_objects as go


def make_blob(n: int) -> np.ndarray:
    xx, yy = np.meshgrid(np.arange(n), np.arange(n))
    return np.exp(-((xx - n // 2) ** 2 + (yy - n // 2) ** 2) / (2 * (n // 2) ** 2))


if __name__ == "__main__":
    n = 101
    x = np.arange(n)
    blob = make_blob(n)
    fig = go.Figure(data=go.Heatmap(x=x, y=x, z=blob, type="heatmap", colorscale="Viridis"))
    fig.add_scatter(x=x, y=x)
    fig.update_xaxes(range=(0, n - 1))
    fig.update_yaxes(range=(0, n - 1))
    fig.show()

gives blob with diagonal line

But pressing “Autoscale” on the toolbar will introduce extra padding at the y-axis: autoscaled blob with diagonal line

Although it can be removed with “Reset axes”, can I make them not appear in the first place? I found this issue on GitHub but not sure how relevant that is.


Solution

  • This is occurring because by default, plotly autoscales the yaxis with padding (y_max - y_min) / 16. Since it seems like Reset Axes does the same thing you want the autoscale to do, you can just remove autoscale entirely:

    fig.update_layout(modebar_remove=['autoScale'])
    

    enter image description here