我有兩個 xy 坐標串列,用于繪制兩條曲線。我對曲線上方的區域感興趣,所以我使用了 fill_between 來得到這個:

現在,我想要的是一種獲取未被彩色區域覆寫的坐標的方法,因此我可以繪制第三條曲線,就像我在下面的示例中使用 Paint 所做的紅色曲線一樣:

我嘗試對串列進行排序,然后比較每一對以找到具有較低 y 值的串列,但這不起作用,因為每個串列可以具有不同的大小和不同的 x 值。我還發現了一些關于交叉乘積的線索,但這些線索使用的是直線,我無法理解如何將其外推到我的案例中。
這是一個mwe:
import matplotlib.pyplot as plt
points_x = [1,3,5,7,9,11,13,15,17,19]
points_y = [10,8,7,6,3,5,3,9,7,6]
points_x2= [0,2,4,8,10,12,14,15,17,19,20,21,22]
points_y2 = [12,10,9,4,2,7,3,8,8,8,8,8,8]
plt.scatter(points_x, points_y, color="blue")
plt.scatter(points_x2, points_y2, color="green")
plt.fill_between(points_x, points_y, plt.ylim()[1], color='blue', alpha=0.5)
plt.fill_between(points_x2, points_y2, plt.ylim()[1], color='green', alpha=0.5)
#way to make a points_x3/points_y3 with only the coordinates at the edge of the
#overlapped areas
plt.show()
(我在想出正確的術語來定義我的問題時遇到了麻煩(非母語人士并且不習慣很多數學術語),所以我為可能提出重復問題而道歉)
uj5u.com熱心網友回復:
您可以將兩條曲線組織到一個共同的 x 軸上,然后計算它們的最小值:
import matplotlib.pyplot as plt
import numpy as np
points_x = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
points_y = [10, 8, 7, 6, 3, 5, 3, 9, 7, 6]
points_x2 = [0, 2, 4, 8, 10, 12, 14, 15, 17, 19, 20, 21, 22]
points_y2 = [12, 10, 9, 4, 2, 7, 3, 8, 8, 8, 8, 8, 8]
plt.scatter(points_x, points_y, color="blue")
plt.scatter(points_x2, points_y2, color="green")
plt.fill_between(points_x, points_y, plt.ylim()[1], color='blue', alpha=0.5)
plt.fill_between(points_x2, points_y2, plt.ylim()[1], color='green', alpha=0.5)
# way to make a points_x3/points_y3 with only the coordinates at the edge of the
# overlapped areas
x_long = np.unique(np.append(points_x, points_x2))
y_long = np.interp(x_long, points_x, points_y, left=np.nan, right=np.nan)
y2_long = np.interp(x_long, points_x2, points_y2, left=np.nan, right=np.nan)
y_min = np.nanmin([y_long, y2_long], axis=0)
plt.plot(x_long, y_min, color='red', ls='--', alpha=0.5, lw=4)
plt.show()

uj5u.com熱心網友回復:
如果我理解正確,您想要的稱為凸包,您可以使用 scipy 計算它:
from scipy.spatial import ConvexHull
points_x = [1,3,5,7,9,11,13,15,17,19]
points_y = [10,8,7,6,3,5,3,9,7,6]
points_x2= [0,2,4,8,10,12,14,15,17,19,20,21,22]
points_y2 = [12,10,9,4,2,7,3,8,8,8,8,8,8]
# making array of x/y coordinates
a = np.array([points_x points_x2, points_y points_y2]).T
min_x = a[:,0].min()
max_x = a[:,0].max()
max_y = a[:,1].max() 1 # arbitrary 1 for ylim
# concatenate extra points to array
a = np.r_[a,np.array([[min_x, max_y], [max_x, max_y]])]
# compute the convex hull
hull = ConvexHull(a)
plt.scatter(points_x, points_y, color="blue")
plt.scatter(points_x2, points_y2, color="green")
plt.fill_between(points_x, points_y, plt.ylim()[1], color='blue', alpha=0.5)
plt.fill_between(points_x2, points_y2, plt.ylim()[1], color='green', alpha=0.5)
idx = np.r_[hull.vertices,hull.vertices[0]]
plt.plot(a[idx,0], a[idx,1], 'r', lw=2)
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/398879.html
標籤:Python matplotlib 阴谋 曲线
