本文介绍了查找叉积以查找MatplotLib中线上方/下方的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 MatPlotLib 中画一条线,并根据斜率找到该线上方或下方的所有点.

阅读此内容后

I am trying to draw a line in MatPlotLib , and find all points above or below the line depending on the slope.

After reading this post, and reading about Cross Product, I believe this is the best approach for me to check the points.

I am unsure what would be the most optimal way to implement this in python.

v1 = {x2-x1, y2-y1}   # Vector 1
v2 = {x2-xA, y2-yA}   # Vector 2
xp = v1.x*v2.y - v1.y*v2.x  # Cross product

Has anyone tried implementing something similar ?

Is there some other way for me to find if points on the plot are above or below a line in MatPlotLib ?

解决方案

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()

这篇关于查找叉积以查找MatplotLib中线上方/下方的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 01:16