简体   繁体   English

在Python中绘制切线图(matplotlib)

[英]Drawing tangent plot in Python (matplotlib)

Today I decided to write simple program in Python, just to practice before exam. 今天我决定用Python编写简单的程序,只是为了在考试之前练习。 Firstly, I wanted to draw sin and cos plot, which wasn't so hard. 首先,我想绘制罪和cos的情节,这并不是那么难。 But then, I decided to challenge myself and draw tangent plot. 但后来,我决定挑战自己,画出切线的情节。

import pylab as p

x= p.arange(-1.0,1.0,0.1)
y= (p.sin(2*p.pi*x)) / (p.cos(2*p.pi*x))

p.plot(x,y,'g-',lw=1)
p.show()

It returns... ugh... this: 它返回......呃......这个:

在此输入图像描述

As you can see, it looks more like ECK plot than tangent plot. 如您所见,它看起来更像是ECK图而不是切线图。 Does anyone knows what's wrong? 有谁知道什么是错的?

If you increase the number of points in x , 如果增加x的点数,

import pylab as p
import numpy as np
x = p.linspace(-1.0, 1.0, 1000)
y = (p.sin(2 * p.pi * x)) / (p.cos(2 * p.pi * x))
p.plot(x, y, 'g-', lw=1)
p.show()

you get something like this: 你得到这样的东西: 在此输入图像描述

Notice how large the y-range is getting. 注意y-range有多大。 Matplotlib is not able to show you much of the small values in the tangent curve because the range is so large. Matplotlib无法显示切线曲线中的大部分小值,因为范围太大。

The plot can be improved by ignoring the extremely large values near the asymptotes. 通过忽略渐近线附近的极大值可以改善该图。 Using Paul's workaround to handle asymptotes, 使用Paul的解决方法来处理渐近线,

import pylab as p
import numpy as np
x = p.linspace(-1.0, 1.0, 1000)
y = (p.sin(2 * p.pi * x)) / (p.cos(2 * p.pi * x))

tol = 10
y[y > tol] = np.nan
y[y < -tol] = np.nan

p.plot(x, y, 'g-', lw=1)
p.show()

you get 你得到

在此输入图像描述

import pylab as p

x= p.arange(-1.0,1.0,0.01)  # <- 0.01 step size.
y= (p.sin(2*p.pi*x)) / (p.cos(2*p.pi*x))
# y = p.tan(2*p.pi*x)
p.plot(x,y,'g-',lw=1)
p.ylim([-4, 4]) # <- Restricting the ylim so we don't see the ~inf values. 
p.show()

This will be the result if you don't set ylim. 如果你没有设置ylim,这将是结果。 (the values approach infinity) (值接近无穷大)

没有设置ylim的结果

Result with setting ylim. 设置ylim的结果。

结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM