Add x=y (45 degree) line within matplotlib axis limits

In matplotlib <= 3.2

x = np.linspace(*ax.get_xlim())
ax.plot(x, x)

In matplotlib >= 3.3

matplotlib 3.3 added the function ax.axline, which can do this better and still works if the axes limits are changed:

ax.axline([0, 0], [1, 1])

If 0 <= X <= 1 and 0 <= Y <= 1, this works for me:

import matplotlib.pyplot as plt

plt.scatter(X, Y)
plt.plot([0, 1], [0, 1], color = 'black', linewidth = 2)
plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)

You could adjust the limits, of course.


Another appraoch.

xpoints = ypoints = plt.xlim()
plt.plot(xpoints, ypoints, linestyle='--', color='k', lw=3, scalex=False, scaley=False)

Source