set_data and autoscale_view matplotlib

33

我有多条线要绘制在同一坐标轴上,并且每个线都是动态更新的(我使用set_data),问题是我不知道每条线的x和y限制。而axes.autoscale_view(True,True,True)/axes.set_autoscale_on(True)并没有发挥预期作用。如何自动缩放我的坐标轴?

import matplotlib.pyplot as plt

fig = plt.figure()
axes = fig.add_subplot(111)

axes.set_autoscale_on(True)
axes.autoscale_view(True,True,True)

l1, = axes.plot([0,0.1,0.2],[1,1.1,1.2])
l2, = axes.plot([0,0.1,0.2],[-0.1,0,0.1])

#plt.show() #shows the auto scaled.

l2.set_data([0,0.1,0.2],[-1,-0.9,-0.8])

#axes.set_ylim([-2,2]) #this works, but i cannot afford to do this.  

plt.draw()
plt.show() #does not show auto scaled

我已经参考过这些内容:这篇文章这篇回答。 在我遇到的所有情况中,x和y轴的限制是已知的。我在坐标系上有多条线,并且它们的范围会改变,跟踪整个数据的最大值并不实际。

经过一些探索,我发现了下面这个方法:

xmin,xmax,ymin,ymax = matplotlib.figure.FigureImage.get_extent(FigureImage) 

但是在这里,我不知道如何从Figure实例中访问FigureImage。

使用matplotlib 0.99.3

1个回答

53

matplotlib自动缩放视图文档中得知:

当已添加到Axes实例的对象的数据发生更改时,数据限制不会自动更新。在这种情况下,在调用autoscale_view之前,请使用matplotlib.axes.Axes.relim()。

所以,在set_data调用后,在plt.draw()调用之前,您需要添加两行代码:

axes.relim()
axes.autoscale_view(True,True,True)

十年过去了,它仍然很好地完成了工作! - raphael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接