如何用虚线绘制渐近线?

how to draw an asymptote with a dashed line?

我想用虚线绘制 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$'))

有趣的问题。我的方法是通过检查函数的导数来寻找不连续点,并根据这些不连续点的位置分离原始函数。

所以对于 tan(x),因为导数总是正的(在渐近线之外)我们寻找 np.diff(y) < 0 的点。基于先前条件为真的所有位置,我们将原始函数分成多个段并单独绘制它们(具有相同的绘图属性,因此线条看起来相同),然后分别绘制黑色虚线。以下代码显示了此工作原理:

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.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))

# Search for points with negative slope
dydx = np.diff(y)
negativeSlopeIdx = np.nonzero(dydx < 0)[0]

# Take those points and parse the original function into segments to plot
yasymptote = np.array([-4, 4])
iprev = 0
for i in negativeSlopeIdx:
    ax.plot(x[iprev:i-1]/np.pi, y[iprev:i-1], "b", linewidth=2)
    ax.plot(np.array([x[i], x[i]])/np.pi, yasymptote, "--k")
    iprev = i+1


ax.plot(x[iprev:]/np.pi, y[iprev:], "b", linewidth=2)
plt.show()

最终情节如下: