Skip to content

Commit 800e6b7

Browse files
committed
DOC: add animation examples to show animated subplots
1 parent 4a5d09c commit 800e6b7

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

examples/animation/multiple_axes.py

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
"""
2+
=======================
3+
Multiple axes animation
4+
=======================
5+
6+
This example showcases:
7+
8+
how animation on subplots works,
9+
10+
using a figure artist in the animation.
11+
12+
"""
13+
14+
import numpy as np
15+
import matplotlib.pyplot as plt
16+
import matplotlib.animation as animation
17+
from matplotlib.patches import ConnectionPatch
18+
19+
fig, (axl, axr) = plt.subplots(
20+
ncols=2,
21+
sharey=True,
22+
figsize=(6, 2),
23+
gridspec_kw=dict(width_ratios=[1, 3], wspace=0),
24+
)
25+
axl.set_aspect(1)
26+
axr.set_box_aspect(1 / 3)
27+
axr.yaxis.set_visible(False)
28+
axr.xaxis.set_ticks([0, np.pi, 2 * np.pi], ["0", r"$\pi$", r"$2\pi$"])
29+
30+
# draw circle with initial point in left Axes
31+
x = np.linspace(0, 2 * np.pi, 50)
32+
axl.plot(np.cos(x), np.sin(x), "k", lw=0.3)
33+
(point,) = axl.plot(0, 0, "o")
34+
35+
# draw full curve to set view limits in right Axes
36+
(sine,) = axr.plot(x, np.sin(x))
37+
38+
# draw connecting line between both graphs
39+
con = ConnectionPatch(
40+
(1, 0),
41+
(0, 0),
42+
"data",
43+
"data",
44+
axesA=axl,
45+
axesB=axr,
46+
color="C0",
47+
ls="dotted",
48+
)
49+
# in order to use blitting, con needs to be added to an Axes (not fig)
50+
fig.add_artist(con)
51+
52+
53+
def animate(i):
54+
pos = np.cos(i), np.sin(i)
55+
point.set_data(*pos)
56+
x = np.linspace(0, i, int(i * 25 / np.pi))
57+
sine.set_data(x, np.sin(x))
58+
con.xy1 = pos
59+
con.xy2 = i, pos[1]
60+
return point, sine, con
61+
62+
63+
ani = animation.FuncAnimation(
64+
fig,
65+
animate,
66+
interval=50,
67+
blit=False, # blitting can't be used with Figure artists
68+
frames=x,
69+
repeat_delay=100,
70+
)
71+
72+
plt.show()
73+
74+
#############################################################################
75+
#
76+
# .. admonition:: References
77+
#
78+
# The use of the following functions, methods, classes and modules is shown
79+
# in this example:
80+
#
81+
# - `matplotlib.patches.ConnectionPatch`
82+
# - `matplotlib.animation.FuncAnimation`

0 commit comments

Comments
 (0)