如何使用matplotlib检测是否存在交集?
How to detect if there is intersection using matplotlib?
我正在使用 matplotlib 绘制这两个折线图。但是,只有有时我的图表才会有交集。如何检测我的折线图是否有交点?
df = pd.read_csv("test.csv")
df2 = pd.read_csv("test2.csv")
x1 = df['A'].tolist()
x1 = np.array(x1)
y1 = df['D'].tolist()
y1 = np.array(y1)
x2 = df2['X'].tolist()
x2 = np.array(x2)
y2 = df2['Y'].tolist()
y2 = np.array(y2)
plt.plot(x1,y1)
plt.plot(x2,y2)
plt.show()
您可以计算交点索引:
idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten()
如果有一个或多个交点,idx
是一个交点列表,否则是一个空列表。
一个或多个路口
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0, 10, 1000)
x2 = np.linspace(-2, 5, 1000)
y1 = np.sin(x1)
y2 = np.cos(x2) + 1
idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten()
fig, ax = plt.subplots()
ax.plot(x1, y1, 'blue')
ax.plot(x2, y2, 'red')
plt.show()
print(len(idx))
2
无交集
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0, 10, 1000)
x2 = np.linspace(-2, 5, 1000)
y1 = np.sin(x1)
y2 = np.cos(x2) + 2
idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten()
fig, ax = plt.subplots()
ax.plot(x1, y1, 'blue')
ax.plot(x2, y2, 'red')
plt.show()
print(len(idx))
0
如果 y 值在某个点相互交叉,此代码将打印 'intersect'。
mark = y1[0]-y2[0]
for i in range(len(y1)):
if mark > 0:
if y1[i]-y2[i] < 0:
print('intersect')
elif mark < 0:
if y1[i]-y2[i] > 0:
print('intersect')
我正在使用 matplotlib 绘制这两个折线图。但是,只有有时我的图表才会有交集。如何检测我的折线图是否有交点?
df = pd.read_csv("test.csv")
df2 = pd.read_csv("test2.csv")
x1 = df['A'].tolist()
x1 = np.array(x1)
y1 = df['D'].tolist()
y1 = np.array(y1)
x2 = df2['X'].tolist()
x2 = np.array(x2)
y2 = df2['Y'].tolist()
y2 = np.array(y2)
plt.plot(x1,y1)
plt.plot(x2,y2)
plt.show()
您可以计算交点索引:
idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten()
如果有一个或多个交点,idx
是一个交点列表,否则是一个空列表。
一个或多个路口
import numpy as np import matplotlib.pyplot as plt x1 = np.linspace(0, 10, 1000) x2 = np.linspace(-2, 5, 1000) y1 = np.sin(x1) y2 = np.cos(x2) + 1 idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten() fig, ax = plt.subplots() ax.plot(x1, y1, 'blue') ax.plot(x2, y2, 'red') plt.show()
print(len(idx)) 2
无交集
import numpy as np import matplotlib.pyplot as plt x1 = np.linspace(0, 10, 1000) x2 = np.linspace(-2, 5, 1000) y1 = np.sin(x1) y2 = np.cos(x2) + 2 idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten() fig, ax = plt.subplots() ax.plot(x1, y1, 'blue') ax.plot(x2, y2, 'red') plt.show()
print(len(idx)) 0
如果 y 值在某个点相互交叉,此代码将打印 'intersect'。
mark = y1[0]-y2[0]
for i in range(len(y1)):
if mark > 0:
if y1[i]-y2[i] < 0:
print('intersect')
elif mark < 0:
if y1[i]-y2[i] > 0:
print('intersect')