How to draw a diagonal line in the background of a scatter plot?

In order to more easily compare correlation of scatter-plots to identity mapping, it would be great to have the first diagonal line being plotted just as the x-y-grid in the background of the plot.

I played with

    fig.update_layout(
        shapes=[
            dict(
                type= 'line',
                yref= 'y', y0=-1000, y1= 1000,
                xref= 'x', x0=-1000, x1= 1000
            )
        ])

but that obviously changes the plot extent. I chose arbitrarily high extent in order to cover all real value ranges.

I guess, there must be a more straight-forward way to add graph elements in the background (not taking any own extent)?

You can define the line in the paper coordinate instead of in the data’s coordinate.

fig.update_layout(shapes = [{'type': 'line', 'yref': 'paper', 'xref': 'paper', 'y0': 0, 'y1': 1, 'x0': 0, 'x1': 1}])

You will also need to set the xaxis_range and yaxis_range to be the same, otherwise, it won’t be a 1:1 line. Additionally, you may want to specify 'layer': 'below' so that the line renders behind the scatter points.

Not great, when zoomed in you get the wrong diagonal. The line should eb according to the true coordinates.

import plotly.io as pio
pio.renderers.default = 'iframe'
fig = px.scatter(df, x='val_f1', y='test_f1', hover_data=['ID'])
# Add diagonal line x=y
fig.add_shape(
    type="line",
    x0=fig.data[0].x.min(), y0=fig.data[0].x.min(),
    x1=fig.data[0].x.max(), y1=fig.data[0].x.max(),
    line=dict(color="red", dash="dash")
)