How to add a y=x line in a scatterplot with matplotlib
While there are such things as axvline
and axhline
, and their less popular, but more general, sibling plt.axline
. You can specify a pair of points, or a starting point and a slope to draw an infninite line:
plt.axline([0, 0], slope=1)
Another approach is to draw a line in the region of your data:
xmin = val1.min()
xmax = val1.max()
ymin = val2.min()
ymax = val2.max()
xmargin = 0.1 * (xmax - xmin)
ymargin = 0.1 * (ymax - ymax)
margin = 0.5 * (xmargin + ymargin)
cmin = max(ymin, xmin)
cmax = min(xmax, ymax)
plt.plot(*[[cmin - margin, cmax + margin]] * 2)
Both methods are shown below with plt.axis('equal')
and the following dataset:
val1, val2 = np.random.uniform([10, 20], size=(100, 2)).T