在 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()
第一个绘图命令从 [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()