使用matplotlib设置xlim和ylim(奇怪的是)

Kri*_*nan 3 python matplotlib

# the first plot DOES NOT set the xlim and ylim properly 
import numpy as np
import pylab as p

x = np.linspace(0.0,5.0,20)
slope = 1.0 
intercept = 3.0 
y = slope*x + intercept
p.set_xlim = ([0.0,10.0])
p.set_ylim = ([0.0,10.0])
p.plot(x,y)
p.show()
p.clf()

def xyplot():
    slope = 1.0
    intercept = 3.0
    x = np.linspace(0.0,5.0,20)
    y = slope*x + intercept 
    p.xlim([0.0,10.0])
    p.ylim([0.0,10.0])
    p.plot(x,y)
    p.show()

# if I place the same exact code a a function, the xlim and ylim
# do what I want ...

xyplot()    
Run Code Online (Sandbox Code Playgroud)

tbe*_*lay 6

你正在设置set_xlimset_ylim不是调用它.你在哪里:

p.set_xlim = ([0.0,10.0])
p.set_ylim = ([0.0,10.0])
Run Code Online (Sandbox Code Playgroud)

你应该有:

p.set_xlim([0.0,10.0])
p.set_ylim([0.0,10.0])
Run Code Online (Sandbox Code Playgroud)

当您进行更改时,您会注意到set_xlim并且set_ylim无法调用它,因为它们在pylab命名空间中不存在.pylab.xlim是获取当前轴对象并调用该对象set_xlim方法的快捷方式.你可以自己做:

ax = p.subplot(111)
ax.set_xlim([0.0,10.0])
ax.set_ylim([0.0,10.0])
Run Code Online (Sandbox Code Playgroud)