set_data 和 autoscale_view 在 matplotlib 中的使用
我有多条线要在同一个坐标轴上绘制,而且这些线是动态更新的(我使用了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的范围都是已知的。我在坐标轴上有多条线,它们的范围会变化,跟踪整个数据的最大y值并不实际。
稍微探索了一下,我找到了这个,
xmin,xmax,ymin,ymax = matplotlib.figure.FigureImage.get_extent(FigureImage)
但在这里,我仍然不知道如何从Figure实例中访问FigureImage。
我使用的是matplotlib 0.99.3
1 个回答
53
来自 matplotlib 关于 autoscale_view 的文档:
当你在一个 Axes 实例中添加了艺术家(比如图形、线条等)后,如果这些艺术家的数据发生了变化,数据的范围不会自动更新。在这种情况下,你需要在调用 autoscale_view 之前,先使用 matplotlib.axes.Axes.relim()。
所以,在你调用 plt.draw()
之前,需要在 set_data
调用后添加两行代码:
axes.relim()
axes.autoscale_view(True,True,True)