1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python matplotlib散点图-python matplotlib更新函数的散点图

python matplotlib散点图-python matplotlib更新函数的散点图

时间:2020-11-02 08:53:15

相关推荐

python matplotlib散点图-python matplotlib更新函数的散点图

有几种方法可以对matplotlib图进行动画处理.在下文中,我们将使用散点图查看两个最小示例.

(a)使用交互式模式plt.ion()

要进行动画制作,我们需要一个事件循环.获取事件循环的一种方法是使用plt.ion()(“交互式打开”).然后需要首先绘制图形,然后可以循环更新绘图.在循环内部,我们需要绘制画布并为窗口引入一点暂停来处理其他事件(如鼠标交互等).没有这个暂停,窗口就会冻结.最后我们调用plt.waitforbuttonpress()让窗口保持打开状态,即使动画完成后也是如此.

import matplotlib.pyplot as plt

import numpy as np

plt.ion()

fig, ax = plt.subplots()

x, y = [],[]

sc = ax.scatter(x,y)

plt.xlim(0,10)

plt.ylim(0,10)

plt.draw()

for i in range(1000):

x.append(np.random.rand(1)*10)

y.append(np.random.rand(1)*10)

sc.set_offsets(np.c_[x,y])

fig.canvas.draw_idle()

plt.pause(0.1)

plt.waitforbuttonpress()

(b)使用FuncAnimation

上面的大部分都可以使用matplotlib.animation.FuncAnimation自动完成.FuncAnimation将处理循环和重绘,并将在给定的时间间隔后不断调用函数(在本例中为animate()).只有在调用plt.show()时动画才会启动,从而在绘图窗口的事件循环中自动运行.

import matplotlib.pyplot as plt

import matplotlib.animation

import numpy as np

fig, ax = plt.subplots()

x, y = [],[]

sc = ax.scatter(x,y)

plt.xlim(0,10)

plt.ylim(0,10)

def animate(i):

x.append(np.random.rand(1)*10)

y.append(np.random.rand(1)*10)

sc.set_offsets(np.c_[x,y])

ani = matplotlib.animation.FuncAnimation(fig, animate,

frames=2, interval=100, repeat=True)

plt.show()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。