As seen e.g. in this question the cross product can indeed be used to determine whether a point lies above or below a line which is defined by two points.
So let a
and b
be two points defining a line, and p
a (set of) point(s) for which we want to know the relative position to the line. Then if
numpy.cross(p-a, b-a) < 0
is True
the point(s) lie above the line.
To be accurate here, "above" means that looking from point a
towards point b
, the point p
lies to the left of the line.
This can be used to colorize points in a scatter plot differently depending on whether they're above or below the line, as seem below:
import numpy as np
import matplotlib.pyplot as plt
isabove = lambda p, a,b: np.cross(p-a, b-a) < 0
a = np.array([1,1])
b = np.array([4,3])
p1 = np.array([2,4])
p2 = np.array([3,1])
p = np.array([p1,p2])
fig, (ax,ax2) = plt.subplots(ncols=2, sharex=True, sharey=True)
ax.plot([a[0],b[0]],[a[1],b[1]], marker="o", color="k")
ax.scatter(p[:,0],p[:,1], c=isabove(p,a,b), cmap="bwr", vmin=0, vmax=1)
p = np.random.rand(10,2)*5
ax2.plot([a[0],b[0]],[a[1],b[1]], marker="o", color="k")
ax2.scatter(p[:,0],p[:,1], c=isabove(p,a,b), cmap="bwr", vmin=0, vmax=1)
ax.set_xlim(0,6)
ax.set_ylim(0,6)
plt.show()
