Python 使用 matplotlib 时设置 xlim 和 ylim(奇怪的东西)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18808218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:55:12  来源:igfitidea点击:

setting xlim and ylim while using matplotlib (something strange)

pythonmatplotlib

提问by Krishnan

# 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()    

回答by tbekolay

You are setting set_xlimand set_yliminstead of calling it. Where you have:

您正在设置set_xlimset_ylim不是调用它。你有:

p.set_xlim = ([0.0,10.0])
p.set_ylim = ([0.0,10.0])

you should have:

你应该有:

p.set_xlim([0.0,10.0])
p.set_ylim([0.0,10.0])

When you make that change, you'll notice that set_xlimand set_ylimcan't be called because they don't exist in the pylabnamespace. pylab.xlimis a shortcut that gets the current axes object and calls that object's set_xlimmethod. You could do this yourself with:

当你做出的改变,你会发现,set_xlimset_ylim不能说是因为它们没有在存在pylab命名空间。pylab.xlim是获取当前坐标区对象并调用该对象set_xlim方法的快捷方式。你可以自己做:

ax = p.subplot(111)
ax.set_xlim([0.0,10.0])
ax.set_ylim([0.0,10.0])