4

我有以下代码:

from mpl_toolkits.axes_grid.axislines import SubplotZero
from matplotlib.transforms import BlendedGenericTransform
import matplotlib.pyplot as plt
import numpy

if 1:
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    ax.axhline(linewidth=1.7, color="black")
    ax.axvline(linewidth=1.7, color="black")

    plt.xticks([1])
    plt.yticks([])

    ax.text(0, 1.05, 'y', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')
    ax.text(1.05, 0, 'x', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    x = numpy.linspace(-1, 1, 10000)
    ax.plot(x, numpy.tan(2*(x - numpy.pi/2)), linewidth=1.2, color="black")

    plt.ylim(-5, 5)
    plt.savefig('graph.png')

这产生了这个图: 图形

如您所见,不仅绘制了棕褐色图,而且还添加了一部分线来连接棕褐色图的渐近区域,通常是渐近线所在的位置。

是否有一些内置方法可以跳过该部分?或者我会绘制由渐近线界定的独立不相交的 tan 域(如果你明白我的意思)?

4

2 回答 2

6

您可以尝试:设置一个有限阈值并修改您的函数以在这些点之后提供非有限值。实用代码修改:

yy = numpy.tan(2*(x - numpy.pi/2))
threshold = 10000
yy[yy>threshold] = numpy.inf
yy[yy<-threshold] = numpy.inf
ax.plot(x, yy, linewidth=1.2, color="black")

结果是:

结果

于 2013-07-15T08:39:49.687 回答
0

在此处输入图像描述此代码为切线函数创建一个图形和一个子图。当 cos(x) 趋于 0 时插入 NaN(NaN 表示“不是数字”并且 NaN 未绘制或连接)。由 k-donn ( https://pypi.org/project/matplot-fmt-pi/ ) 创建的 matplot-fmt-pi 用于更改格式化程序以使 x 标签和刻度对应于小数格式的 π/8 的倍数。绘图格式(网格、图例、限制、轴)按注释执行。

import matplotlib.pyplot as plt
import numpy as np
from matplot_fmt_pi import MultiplePi

fig, ax = plt.subplots()        # creates a figure and one subplot
x = np.linspace(-2 * np.pi, 2 * np.pi, 1000)
y = np.tan(x)
y[np.abs(np.cos(x)) <= np.abs(np.sin(x[1]-x[0]))] = np.nan
# This operation inserts a NaN where cos(x) is reaching 0
# NaN means "Not a Number" and NaNs are not plotted or connected
ax.plot(x, y, lw=2, color="blue", label='Tangent')
# Set up grid, legend, and limits
ax.grid(True)
ax.axhline(0, color='black', lw=.75)
ax.axvline(0, color='black', lw=.75)
ax.set_title("Trigonometric Functions")
ax.legend(frameon=False)    # remove frame legend frame
# axis formatting
ax.set_xlim(-2 * np.pi, 2 * np.pi)
pi_manager = MultiplePi(8)          # number= ticks between 0 - pi
ax.xaxis.set_major_locator(pi_manager.locator())
ax.xaxis.set_major_formatter(pi_manager.formatter())
plt.ylim(top=10)  # y axis limit values
plt.ylim(bottom=-10)
y_ticks = np.arange(-10, 10, 1)
plt.yticks(y_ticks)
fig
[![enter image description here][1]][1]plt.show()
于 2020-07-12T23:58:59.837 回答