我正在使用matplotlib來繪制這兩個直線圖。然而,只有有時我的圖形會有一個交點。我怎樣才能檢測我的線圖是否有交集呢?
df = pd.read_csv("test.csv"/span>)
df2 = pd.read_csv("test2.csv")
x1 = df['A'/span>].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()
uj5u.com熱心網友回復:
你可以用以下方法來計算交點的索引:
idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten()
如果有一個或多個交叉點,idx是一個交叉點indeces的串列,否則它是一個空串列。
一個或多個交叉點
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(span class="hljs-bilt_in">len(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) 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(span class="hljs-bilt_in">len(idx)
uj5u.com熱心網友回復:
如果y值在某一點上相互交叉,這段代碼會列印出'intersect'。
mark = y1[0] -y2[0]
for i in range(len(y1))。
if mark > 0:
if y1[i]-y2[i] < 0:
print('intersect'/span>)
elif mark < 0:
if y1[i]-y2[i] > 0:
print('intersect'/span>)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/326882.html
標籤:



