[英]How to find the intersection of triangle and the curves in 2D?
我已经绘制了一个三角形广告两条线。 我想 plot 用其他样式的三角形内的线条部分。 请问怎么找路口? 非常感谢。
import matplotlib.pyplot as plt
import numpy as np
from sympy import *
a1 = 1080
a2 = 350
c1 = -7
c2 = 0
d = 7
x = np.linspace(0,100,500)
y1 = a1/(x-c1)-d
y2 = a2/(x-c2)
fig, ax = plt.subplots()
plt.rcParams["figure.figsize"] = [10, 3]
I1 = 23
x_end = 70
plt.xlim(0,x_end)
plt.ylim(0,50)
# Plot curves
plt.plot(x[10:], y1[10:], c = 'red')
plt.plot(x[10:], y2[10:], c = 'blue')
# Plot triangle
shift = 15
triangle = np.array([[0,I1], [x_end,I1+shift], [x_end, I1-shift]])
plt.scatter(triangle[:, 0], triangle[:, 1], s = 0, color = 'grey')
t1 = plt.Polygon(triangle[:3,:])
plt.gca().add_patch(t1)
x = symbols('x')
intercept = solve(a1/(x-c1)-d, (322+3*x)/14)
print(intercept)
plt.show()
您可以使用fill_between
并将三角形设置为 clip_path。 需要更改 zorder 以显示三角形顶部的绿色区域。
import matplotlib.pyplot as plt
import numpy as np
a1 = 1080
a2 = 350
c1 = -7
c2 = 0
d = 7
x = np.linspace(0, 100, 500)
y1 = a1 / (x - c1) - d
y2 = a2 / (x - c2)
fig, ax = plt.subplots(figsize=(10, 3))
I1 = 23
x_end = 70
plt.xlim(0, x_end)
plt.ylim(0, 50)
# Plot curves
ax.plot(x[10:], y1[10:], c='red')
ax.plot(x[10:], y2[10:], c='blue')
# Plot triangle
shift = 15
triangle = np.array([[0, I1], [x_end, I1 + shift], [x_end, I1 - shift]])
ax.scatter(triangle[:, 0], triangle[:, 1], s=1, color='grey')
t1 = plt.Polygon(triangle[:3, :])
ax.add_patch(t1)
ax.fill_between(x[10:], y1[10:], y2[10:], facecolor='lime', clip_path=t1, zorder=2)
plt.show()
PS:请注意,对于 x 的第一个值 (0),您的公式y2 = a2 / (x - c2)
除以零。 您可能希望 x 以较大的值开始,例如x = np.linspace(0.1, 100, 500)
。
如果您不想显示三角形,则仍然需要ax.add_patch()
才能使剪辑按预期工作。 您可以使其不可见( t1 = plt.Polygon(triangle[:3, :], color='none')
或t1 = plt.Polygon(triangle[:3, :], visible=False)
)。
正如@swatchai 所评论的,如果您只想要不同的线条样式,您可以剪裁绘制的曲线:
t1 = plt.Polygon(triangle[:3, :], visible=False)
ax.add_patch(t1)
#ax.fill_between(x[10:], y1[10:], y2[10:], facecolor='lime', clip_path=t1, zorder=2)
ax.plot(x[10:], y1[10:], 'w:', clip_path=t1)
ax.plot(x[10:], y2[10:], 'w:', clip_path=t1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.