Drawing Collections
is faster, so I modified the draw()
function of the PathCollection
object returned by scatter()
. The new draw()
uses transData
to calculate the scale of every circle, it uses the size of every circle as diameter.
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()
Here is a frame of the animation: