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

问题描述:

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

I'm plotting data in Python using matplotlib. I am updating the data of the plot based upon some calculations and want the ylim and xlim to be rescaled automatically. Instead what happens is the scale is set based upon the limits of the initial plot. A MWE is

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-data数组从[0,10)开始,其中大部分大于1,但是图形的y-limits仍然为[0,1].

The first plot command generates a plot from [0,1] and I can see everything just fine. At the end, the y-data array goes from [0,10) with most of it greater than 1, but the y-limits of the figure remain [0,1].

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

I know I can manually change the limits using pyplot.ylim(...), but I don't know what to change them to. In the for loop, can I tell pyplot to scale the limits as if it was the first time being plotted?

您将需要更新轴的dataLim,然后基于dataLim更新轴的viewLim.合适的方法是axes.relim()ax.autoscale_view()方法. 您的示例如下所示:

You will need to update the axes' dataLim, then subsequently update the axes' viewLim based on the dataLim. The approrpiate methods are axes.relim() and ax.autoscale_view() method. Your example then looks like:

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