如何用虚线绘制渐近线?

我希望 tg(x) 函数上的渐近线用虚线绘制,但我不知道如何在这段代码中更改它:


import matplotlib.ticker as tck

import matplotlib.pyplot as plt

import numpy as np

f,ax=plt.subplots(figsize=(8,5))

x=np.linspace(-np.pi, np.pi,100)

y=np.sin(x)/np.cos(x)

plt.ylim([-4, 4])

plt.title("f(x) = tg(x)")

plt.xlabel("x")

plt.ylabel("y")

ax.plot(x/np.pi,y)

ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))


慕桂英4014372
浏览 181回答 1
1回答

UYOU

有趣的问题。我的方法是通过检查函数的导数来寻找不连续性,并根据这些不连续性的位置分离原始函数。所以对于tan(x),由于导数总是正的(在渐近线之外),我们寻找 的点np.diff(y) < 0。基于前一个条件为真的所有位置,我们将原始函数拆分为段并单独绘制它们(具有相同的绘图属性,因此线条看起来相同),然后分别绘制黑色虚线。以下代码显示了此工作:import matplotlib.ticker as tckimport matplotlib.pyplot as pltimport numpy as npf,ax=plt.subplots(figsize=(8,5))x=np.linspace(-np.pi, np.pi,100)y=np.sin(x)/np.cos(x)plt.ylim([-4, 4])plt.title("f(x) = tg(x)")plt.xlabel("x")plt.ylabel("y")ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))# Search for points with negative slopedydx = np.diff(y)negativeSlopeIdx = np.nonzero(dydx < 0)[0]# Take those points and parse the original function into segments to plotyasymptote = np.array([-4, 4])iprev = 0for i in negativeSlopeIdx:&nbsp; &nbsp; ax.plot(x[iprev:i-1]/np.pi, y[iprev:i-1], "b", linewidth=2)&nbsp; &nbsp; ax.plot(np.array([x[i], x[i]])/np.pi, yasymptote, "--k")&nbsp; &nbsp; iprev = i+1ax.plot(x[iprev:]/np.pi, y[iprev:], "b", linewidth=2)plt.show()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python