<p>你可以采取几种不同的方法。在</p>
<p>一种是只画出割线的一部分。你可以在任何地方计算它,过滤出比你的“主”曲线大得多或小得多的点,或者你可以计算一个更有限的范围来评估它。在</p>
<p>另一种方法是告诉matplotlib只对“主”曲线进行自动缩放,而对另一条曲线不设置限制。在</p>
<hr/>
<p>首先,我将以稍微不同的方式编写您的示例。你做事的方式没有错,但我觉得这种风格更具可读性:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
def main():
x = np.linspace(-2,2,100)
p1 = 2 #starts from zero
p2 = 50 #starts from zero
y1 = main_func(x)
y2 = calculate_secant(x, y1, p1, p2)
plot(x, y1, y2)
plt.show()
def main_func(x):
return x**2
def calculate_secant(x, y, p1, p2):
points = [p1, p2]
m, b = np.polyfit(x[points], y[points], 1)
return m * x + b
def plot(x, y1, y2):
plt.plot(x, y1)
plt.plot(x, y2)
main()
</code></pre>
<p>我们会得到一个“缩小”的图,你不想要:</p>
<p><a href="https://i.stack.imgur.com/1Qr8b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Qr8b.png" alt="enter image description here"/></a></p>
<hr/>
<p>如果稍微更改<code>plot</code>函数,我们可以告诉matplotlib在绘制第二条直线时不要更改轴限制:</p>
^{pr2}$
<p><a href="https://i.stack.imgur.com/FOqrj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FOqrj.png" alt="enter image description here"/></a></p>
<hr/>
<p>或者,我们可以从绿线中屏蔽出明显大于蓝线的点(关键是下面的第三条线,其他线是相同的,并根据上下文给出:</p>
<pre><code>y1 = main_func(x)
y2 = calculate_secant(x, y1, p1, p2)
y2[y2 < y1] = np.nan
plot(x, y1, y2)
</code></pre>
<p>这将产生(可能是不需要的,可能是期望的)副作用,即剪掉两条线交叉的左侧:</p>
<p><a href="https://i.stack.imgur.com/gDWQZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gDWQZ.png" alt="enter image description here"/></a></p>