Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Update example and docstring to encourage the use of functools.partial
  • Loading branch information
jeffreypaul15 authored and oscargus committed Oct 21, 2022
commit 56192f1c27d1c4f108f8061a159350b1d36a8f95
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')
Comment thread
oscargus marked this conversation as resolved.
Resolved

def init():
ax.set_xlim(0, 2*np.pi)
Comment thread
oscargus marked this conversation as resolved.
Resolved
ax.set_ylim(-1, 1)
return ln,

def update(frame, x, y):
Comment thread
oscargus marked this conversation as resolved.
Resolved
x.append(frame)
y.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,

xdata, ydata = [], []
Comment thread
oscargus marked this conversation as resolved.
Resolved
ani = FuncAnimation(
fig, partial(update, x=xdata, y=ydata),
Comment thread
oscargus marked this conversation as resolved.
Resolved
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