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.

2 Likes