当绘制具有不连续性/渐近线/奇点/等的图形时,是否有任何自动方法可以防止Matplotlib在“中断”中“加入点”? (请参阅下面的代码/图片) 我读到Sage有一个看起来很好的[detect_poles]工具,但我真的希望它能与Matplotlib一起工作。
import matplotlib.pyplot as plt
import numpy as np
from sympy import sympify, lambdify
from sympy.abc import x
fig = plt.figure(1)
ax = fig.add_subplot(111)
# set up axis
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# setup x and y ranges and precision
xx = np.arange(-0.5,5.5,0.01)
# draw my curve
myfunction=sympify(1/(x-2))
mylambdifiedfunction=lambdify(x,myfunction,'numpy')
ax.plot(xx, mylambdifiedfunction(xx),zorder=100,linewidth=3,color='red')
#set bounds
ax.set_xbound(-1,6)
ax.set_ybound(-4,4)
plt.show()
答案 0 :(得分:22)
通过使用masked arrays,您可以避免绘制曲线的选定区域。
要删除x = 2处的奇点:
import matplotlib.numerix.ma as M # for older versions, prior to .98
#import numpy.ma as M # for newer versions of matplotlib
from pylab import *
figure()
xx = np.arange(-0.5,5.5,0.01)
vals = 1/(xx-2)
vals = M.array(vals)
mvals = M.masked_where(xx==2, vals)
subplot(121)
plot(xx, mvals, linewidth=3, color='red')
xlim(-1,6)
ylim(-5,5)
这条简单的曲线可能会更清楚地排除哪些点:
xx = np.arange(0,6,.2)
vals = M.array(xx)
mvals = M.masked_where(vals%2==0, vals)
subplot(122)
plot(xx, mvals, color='b', linewidth=3)
plot(xx, vals, 'rx')
show()
答案 1 :(得分:13)
这可能不是您正在寻找的优雅解决方案,但如果只想在大多数情况下获得结果,您可以将绘制数据的大小值分别“剪切”到+∞
和-∞
。 Matplotlib没有绘制这些。当然,你必须小心,不要让你的分辨率太低或剪裁阈值太高。
utol = 100.
ltol = -100.
yy = 1/(xx-2)
yy[yy>utol] = np.inf
yy[yy<ltol] = -np.inf
ax.plot(xx, yy, zorder=100, linewidth=3, color='red')
答案 2 :(得分:5)
不,我认为没有内置的方法告诉matplotlib
忽略这些
点。毕竟,它只是连接点而对功能一无所知
或者点之间会发生什么。
但是,您可以使用sympy
找到极点,然后将功能的连续部分拼接在一起。在这里,一些公认的丑陋代码确实如此:
from pylab import *
from sympy import solve
from sympy.abc import x
from sympy.functions.elementary.complexes import im
xmin = -0.5
xmax = 5.5
xstep = 0.01
# solve for 1/f(x)=0 -- we will have poles there
discontinuities = sort(solve(1/(1/(x-2)),x))
# pieces from xmin to last discontinuity
last_b = xmin
for b in discontinuities:
# check that this discontinuity is inside our range, also make sure it's real
if b<last_b or b>xmax or im(b):
continue
xi = np.arange(last_b, b, xstep)
plot(xi, 1./(xi-2),'r-')
last_b = b
# from last discontinuity to xmax
xi = np.arange(last_b, xmax, xstep)
plot(xi, 1./(xi-2),'r-')
xlim(xmin, xmax)
ylim(-4,4)
show()