如何将 y=1/x 绘制为单个图形 [英] How to plot y=1/x as a single graph
问题描述
是否有一种简单的方法可以将一个函数在正负趋于无穷大的情况下绘制为单个图,而不将图连接正负两端?
Is there an easy way to plot a function which tends to infinity in the positive and negative as a single plot, without the plot joining both ends of the positive and negative?
例如,使用以下代码绘制y = 1/x可得出结果图:
For example, plotting y=1/x using this code gives the resulting plot:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return 1/x
fx_name = r'$f(x)=\frac{1}{x}$'
x=np.setdiff1d(np.linspace(-10,10,100),[0]) #to remove the zero
y=f(x)
plt.plot(x, y, label=fx_name)
plt.legend(loc='upper left')
plt.show()
但我想要这个输出,我通过绘制两个单独的域来实现:
But I would like this output, which I achieve by plotting two separate domains:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return 1/x
fx_name = r'$f(x)=\frac{1}{x}$'
xfn=np.setdiff1d(np.linspace(-10,0,100),[0])
xfp=np.setdiff1d(np.linspace(0,10,100),[0])
yfn=f(xfn)
yfp=f(xfp)
yf = plt.plot(xfn, yfn, label=fx_name)
plt.plot(xfp, yfp, color=yf[0].get_color())
plt.legend(loc='upper left')
plt.show()
有捷径吗?非常感谢.
在域数组中包含零,并抑制除以零.这会强制返回的共域数组的一个元素为inf",并且不会绘制inf".
Include zero in the domain array, and suppress the divide by zero. This forces one element of the returned co-domain array as "inf", and "inf" is not plotted.
import numpy as np
import matplotlib.pyplot as plt
def f(x):
with np.errstate(divide='ignore', invalid='ignore'):
return 1/x
fx_name = r'$f(x)=\frac{1}{x}$'
x=np.linspace(-10,10,101)
y=f(x)
plt.plot(x, y, label=fx_name)
plt.legend(loc='upper left')
plt.show()
我更喜欢这种方法,因为它避免了对数组的手动操作,并且可以轻松地重用于共享相同域的其他函数(例如y = 1/(x + 2)).感谢大家的贡献.
I prefer this method since it avoids manual manipulation of the array, and can be easily reused for other functions which share the same domain (ex. y=1/(x+2)). Thank you all for contributions.
推荐答案
实际上你想包含 x = 0
因为这导致 y = nan
,形成一个缺口在情节中.
Actually you want to include x = 0
because this results in y = nan
, forming a gap in the plot.
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return 1/x
fx_name = r'$f(x)=\frac{1}{x}$'
# using 101 steps results in in array including the value 0
x=np.linspace(-10,10,101)
# f(0) = nan -> a nan value creates a gap
y=f(x)
plt.plot(x, y, label=fx_name)
plt.legend(loc='upper left')
plt.show()
这篇关于如何将 y=1/x 绘制为单个图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!