Skip to content

Commit

Permalink
Update example and docstring to encourage the use of functools.partial
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffreypaul15 authored and oscargus committed Oct 21, 2022
1 parent 231d1c8 commit 56192f1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
34 changes: 32 additions & 2 deletions doc/api/animation_api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ artist at a global scope and let Python sort things out. For example ::
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from functools import partial

fig, ax = plt.subplots()
xdata, ydata = [], []
Expand All @@ -133,8 +134,37 @@ artist at a global scope and let Python sort things out. For example ::
init_func=init, blit=True)
plt.show()

The second method is to use `functools.partial` to 'bind' artists to
function. A third method is to use closures to build up the required
The second method is to use `functools.partial` to pass arguments to the
function. ::

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from functools import partial

fig, ax = plt.subplots()
ln, = plt.plot([], [], 'ro')

def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,

def update(frame, x, y):
x.append(frame)
y.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,

xdata, ydata = [], []
ani = FuncAnimation(
fig, partial(update, x=xdata, y=ydata),
frames=np.linspace(0, 2 * np.pi, 128),
init_func=init, blit=True)

plt.show()

A third method is to use closures to build up the required
artists and functions. A fourth method is to create a class.

Examples
Expand Down
3 changes: 2 additions & 1 deletion lib/matplotlib/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1564,7 +1564,8 @@ def init_func() -> iterable_of_artists
value is unused if ``blit == False`` and may be omitted in that case.
fargs : tuple or None, optional
Additional arguments to pass to each call to *func*.
Additional arguments to pass to each call to *func*. Note: the use of
`functools.partial` is preferred over *fargs*.
save_count : int, default: 100
Fallback for the number of values from *frames* to cache. This is
Expand Down

0 comments on commit 56192f1

Please sign in to comment.