Drawing Collections
速度更快,所以我修改了draw()
的功能PathCollection
返回的对象scatter()
。新的draw()
uses transData
为了计算每个圆的比例,它使用每个圆的大小作为直径。
import pylab as pl
import numpy as np
from matplotlib.collections import Collection
from matplotlib import transforms
import matplotlib.animation as animation
fig = pl.figure()
N = 40
x, y = np.random.rand(2, N)
color = np.random.rand(N)
r = np.random.rand(N) * 0.05 + 0.05
c = pl.scatter(x, y, s=r, c=color, alpha=0.5, animated=True)
pl.gca().set_aspect("equal")
def draw(self, renderer):
if self._sizes is not None:
m = self.axes.transData.get_matrix()
self._transforms = [
transforms.Affine2D().scale(m[0, 0]*x, m[1, 1]*x)
for x in self._sizes]
return Collection.draw(self, renderer)
c.draw = lambda renderer:draw(c, renderer)
def update_loc(n):
global x2, y2, x, y
n = n % 50
if n == 0:
x2, y2 = np.random.rand(2, N)
x += (x2 - x) * 0.1
y += (y2 - y) * 0.1
c.set_offsets(np.c_[x, y])
return c,
ani = animation.FuncAnimation(fig, update_loc, 2500, interval=50, blit=True)
pl.show()
这是动画的一帧: