Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Matplotlib中自动重新缩放ylim和xlim_Python_Matplotlib - Fatal编程技术网

Python 在Matplotlib中自动重新缩放ylim和xlim

Python 在Matplotlib中自动重新缩放ylim和xlim,python,matplotlib,Python,Matplotlib,我正在使用matplotlib用Python绘制数据。我正在根据一些计算更新绘图数据,并希望ylim和xlim自动重新缩放。取而代之的是,比例是根据初始绘图的限制设置的。MWE是 import random import matplotlib.pyplot as pyplot pyplot.ion() x = range(10) y = lambda m: [m*random.random() for i in range(10)] pLine, = pyplot.plot(x, y(1)

我正在使用matplotlib用Python绘制数据。我正在根据一些计算更新绘图数据,并希望ylim和xlim自动重新缩放。取而代之的是,比例是根据初始绘图的限制设置的。MWE是

import random
import matplotlib.pyplot as pyplot

pyplot.ion()

x = range(10)
y = lambda m: [m*random.random() for i in range(10)]

pLine, = pyplot.plot(x, y(1))

for i in range(10):
    pLine.set_ydata(y(i+1))
    pyplot.draw()
第一个plot命令从
[0,1]
生成一个绘图,我可以很好地看到一切。最后,y数据数组从
[0,10)
开始,其中大部分大于
1
,但图形的y限制仍然是
[0,1]


我知道我可以使用
pyplot.ylim(…)手动更改限制
,但我不知道要将它们更改为什么。在
for
循环中,我可以告诉pyplot缩放限制,就像它是第一次被绘制一样吗?

您需要更新轴的dataLim,然后根据dataLim更新轴的viewLim。合适的方法是
axes.relim()
ax.autoscale\u view()
方法。 您的示例如下所示:

import random
import matplotlib.pyplot as pyplot

pyplot.ion()

x = range(10)
y = lambda m: [m*random.random() for i in range(10)]

pLine, = pyplot.plot(x, y(1))

for i in range(10):
    pLine.set_ydata(y(i+1))

ax = pyplot.gca()

# recompute the ax.dataLim
ax.relim()
# update ax.viewLim using the new dataLim
ax.autoscale_view()
pyplot.draw()

查看这两个相关答案:请注意,如果您以前在相同的轴上使用过
set_xlim()
autoscale_view()
将不起作用。在这种情况下,应改用
autoscale()
(在1.5.x上测试)。看起来,
relim()
autoscale*()
只考虑标记的位置,而忽略错误条。必须有一种方法来计算限制,同时考虑错误条(或通常情况下,绘图上所有绘制的元素),因为默认情况下它们绘制正确。如果使用
ylim
(或
设置ylim
)来“缩放”绘图,然后我无法找到将“取消缩放”回原始视图的方法。这非常有效!我想问一件事。如果与
ax.errorbar(x,y,error)一起使用
,此方法未考虑错误栏,因此错误栏可能会隐藏在轴之后。是否有办法使其解决此问题?谢谢!@zyy不是答案,只是注意:我认为原因是错误栏使用集合,ax.relim()会忽略这些集合:请参阅。