在matplotlib中绘制棕褐色图形

时间:2013-07-15 08:03:01

标签: python graph matplotlib

我有以下代码:

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')

生成此图表: graph

正如您所看到的,不仅草绘了棕褐色图,而且还添加了一部分线来连接棕褐色图的渐近区域,其中渐近线通常是。

是否有一些内置的方法可以跳过该部分?或者我是否会绘制由渐近线限制的棕褐色的不相交域(如果你理解我的意思)?

2 个答案:

答案 0 :(得分: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")

结果:

Result

答案 1 :(得分:0)

enter image description here此代码为切线功能创建一个图形和一个子图。当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()