Ubuntu matplotlib animation save 保存 使用 例子
程序员文章站
2022-03-30 10:42:10
...
animation_demo.py
"""
================
pyplot animation
================
Generating an animation by calling `~.pyplot.pause` between plotting commands.
The method shown here is only suitable for simple, low-performance use. For
more demanding applications, look at the :mod:`animation` module and the
examples that use it.
Note that calling `time.sleep` instead of `~.pyplot.pause` would *not* work.
"""
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
data = np.random.random((50, 50, 50))
fig, ax = plt.subplots()
for i in range(len(data)):
ax.cla()
ax.imshow(data[i])
ax.set_title("frame {}".format(i))
# Note that using time.sleep does *not* work here!
plt.pause(0.1)
import matplotlib
matplotlib.use("Agg")
from matplotlib.animation import ImageMagickWriter
import matplotlib.pyplot as plt
import numpy as np
metadata = dict(title='Darren Movie Test', artist='Matplotlib',
comment='Movie support!')
writer = ImageMagickWriter(fps=15, metadata=metadata)
np.random.seed(19680801)
data = np.random.random((50, 50, 50))
fig, ax = plt.subplots()
with writer.saving(fig, "darren_writer_test.gif", 100):
for i in range(50):
ax.imshow(data[i])
ax.set_title("frame {}".format(i))
writer.grab_frame()
frame_grabbing_sgskip.py
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.animation import FFMpegWriter
np.random.seed(19680801)
metadata = dict(title='Darren Movie Test', artist='Matplotlib', comment='Movie support!')
writer = FFMpegWriter(fps=15, metadata=metadata)
fig = plt.figure()
l, = plt.plot([], [], 'k-o')
plt.xlim(-5, 5)
plt.ylim(-5, 5)
x0, y0 = 0, 0
with writer.saving(fig, "darren_writer_test.mp4", 100):
for i in range(200):
x0 += 0.1 * np.random.randn()
y0 += 0.1 * np.random.randn()
l.set_data(x0, y0)
writer.grab_frame()
可以生成MP4文件。然而MP4文件传不上来,我们把它保存成gif
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.animation import ImageMagickWriter
np.random.seed(19680801)
metadata = dict(title='Darren Movie Test', artist='Matplotlib',
comment='Movie support!')
writer = ImageMagickWriter(fps=15, metadata=metadata)
fig = plt.figure()
l, = plt.plot([], [], 'k-o')
plt.xlim(-5, 5)
plt.ylim(-5, 5)
x0, y0 = 0, 0
with writer.saving(fig, "darren_writer_test.gif", 100):
for i in range(1000):
x0 += 0.1 * np.random.randn()
y0 += 0.1 * np.random.randn()
l.set_data(x0, y0)
writer.grab_frame()
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.animation import ImageMagickWriter
metadata = dict(title='Darren Movie Test', artist='Matplotlib',
comment='Movie support!')
writer = ImageMagickWriter(fps=15, metadata=metadata)
fig, ax = plt.subplots()
line, = ax.plot([],[],lw=2)
ax.grid()
xdata,ydata=[],[]
plt.xlim(0, 10)
plt.ylim(-1.1, 1.1)
def data_gen(t=0):
cnt = 0
while 1:
cnt += 1
t += 0.1
yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
with writer.saving(fig, "darren_writer_test.gif", 50):
f= data_gen()
for i in range(500):
t,y = f.next()
xdata.append(t)
ydata.append(y)
xmin,xmax = ax.get_xlim()
if t >= xmax:
ax.set_xlim(xmin,2*xmax)
ax.figure.canvas.draw()
line.set_data(xdata,ydata)
writer.grab_frame()
animated_histogram.py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import matplotlib.animation as animation
np.random.seed(19680801)
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n
nrects = len(left)
nverts = nrects * (1 + 3 + 1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5, 0] = left
verts[0::5, 1] = bottom
verts[1::5, 0] = left
verts[1::5, 1] = top
verts[2::5, 0] = right
verts[2::5, 1] = top
verts[3::5, 0] = right
verts[3::5, 1] = bottom
patch = None
def animate(i):
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)
top = bottom + n
verts[1::5, 1] = top
verts[2::5, 1] = top
return [patch, ]
fig, ax = plt.subplots()
barpath = path.Path(verts, codes)
patch = patches.PathPatch(
barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
ax.add_patch(patch)
ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())
ani = animation.FuncAnimation(fig, animate, 100, repeat=False, blit=True)
plt.show()
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.animation import ImageMagickWriter
import matplotlib.patches as patches
import matplotlib.path as path
import matplotlib.animation as animation
metadata = dict(title='Darren Movie Test', artist='Matplotlib',
comment='Darren Movie support!')
writer = ImageMagickWriter(fps=15, metadata=metadata)
np.random.seed(19680801)
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n
nrects = len(left)
nverts = nrects * (1 + 3 + 1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5, 0] = left
verts[0::5, 1] = bottom
verts[1::5, 0] = left
verts[1::5, 1] = top
verts[2::5, 0] = right
verts[2::5, 1] = top
verts[3::5, 0] = right
verts[3::5, 1] = bottom
patch = None
fig, ax = plt.subplots()
barpath = path.Path(verts, codes)
patch = patches.PathPatch(barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
ax.add_patch(patch)
ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())
with writer.saving(fig, "darren_writer_test.gif", 100):
for i in range(100):
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)
top = bottom + n
verts[1::5, 1] = top
verts[2::5, 1] = top
writer.grab_frame()
bayes_update.py
"""
================
The Bayes update
================
This animation displays the posterior estimate updates as it is refitted when
new data arrives.
The vertical line represents the theoretical value to which the plotted
distribution should converge.
"""
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def beta_pdf(x, a, b):
return (x**(a-1) * (1-x)**(b-1) * math.gamma(a + b)
/ (math.gamma(a) * math.gamma(b)))
class UpdateDist(object):
def __init__(self, ax, prob=0.5):
self.success = 0
self.prob = prob
self.line, = ax.plot([], [], 'k-')
self.x = np.linspace(0, 1, 200)
self.ax = ax
# Set up plot parameters
self.ax.set_xlim(0, 1)
self.ax.set_ylim(0, 15)
self.ax.grid(True)
# This vertical line represents the theoretical value, to
# which the plotted distribution should converge.
self.ax.axvline(prob, linestyle='--', color='black')
def init(self):
self.success = 0
self.line.set_data([], [])
return self.line,
def __call__(self, i):
# This way the plot can continuously run and we just keep
# watching new realizations of the process
if i == 0:
return self.init()
# Choose success based on exceed a threshold with a uniform pick
if np.random.rand(1,) < self.prob:
self.success += 1
y = beta_pdf(self.x, self.success + 1, (i - self.success) + 1)
self.line.set_data(self.x, y)
return self.line,
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
ud = UpdateDist(ax, prob=0.7)
anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init,
interval=100, blit=True)
plt.show()
import math
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.animation import ImageMagickWriter
metadata = dict(title='Darren Movie Test', artist='Matplotlib',
comment='Darren Movie support!')
writer = ImageMagickWriter(fps=15, metadata=metadata)
def beta_pdf(x, a, b):
return (x**(a-1) * (1-x)**(b-1) * math.gamma(a + b)
/ (math.gamma(a) * math.gamma(b)))
class UpdateDist(object):
def __init__(self, ax, prob=0.5):
self.success = 0
self.prob = prob
self.line, = ax.plot([], [], 'k-')
self.x = np.linspace(0, 1, 100)
self.ax = ax
self.ax.set_xlim(0, 1)
self.ax.set_ylim(0, 15)
self.ax.grid(True)
self.ax.axvline(prob, linestyle='--', color='black')
def init(self):
self.success = 0
self.line.set_data([], [])
return self.line,
def __call__(self, i):
if i == 0:
return self.init()
if np.random.rand(1,) < self.prob:
self.success += 1
y = beta_pdf(self.x, self.success + 1, (i - self.success) + 1)
self.line.set_data(self.x, y)
return self.line,
np.random.seed(19680801)
fig, ax = plt.subplots()
ud = UpdateDist(ax, prob=0.7)
with writer.saving(fig, "darren_writer_test.gif", 100):
for i in range(150):
ud(i)
writer.grab_frame()
double_pendulum_sgskip.py
from numpy import sin, cos
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation
G = 9.8
L1 = 1.0
L2 = 1.0
M1 = 1.0
M2 = 1.0
def derivs(state,t):
dydx = np.zeros_like(state)
dydx[0] = state[1]
del_ = state[2] - state[0]
den1 = (M1 + M2)*L1 - M2*L1*cos(del_)*cos(del_)
dydx[1] = (M2*L1*state[1]*state[1]*sin(del_)*cos(del_)+ M2*G*sin(state[2])*cos(del_)+M2*L2*state[3]*state[3]*sin(del_)-(M1+M2)*G*sin(state[0]))/den1
dydx[2] = state[3]
den2 = (L2/L1)*den1
dydx[3] = (-M2*L2*state[3]*state[3]*sin(del_)*cos(del_)+ (M1+M2)*G*sin(state[0])*cos(del_) - (M1+M2)*L1*state[1]*state[1]*sin(del_)-(M1+M2)*G*sin(state[2]))/den2
return dydx
dt = 0.05
t = np.arange(0.0,20,dt)
th1 = 120.0
w1 = 0.0
th2 = -10.0
w2 = 0.0
state = np.radians([th1,w1,th2,w2])
y = integrate.odeint(derivs,state,t)
x1 = L1*sin(y[:,0])
y1 = -L1*cos(y[:,0])
x2 = L2*sin(y[:,2]) + x1
y2 = -L2*cos(y[:,2]) + y1
fig = plt.figure()
ax = fig.add_subplot(111,autoscale_on=False,xlim=(-2,2),ylim=(-2,2))
ax.set_aspect('equal')
ax.grid()
line, = ax.plot([],[],'o-',lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05,0.9,'',transform=ax.transAxes)
def init():
line.set_data([],[])
time_text.set_text('')
return line,time_text
def animate(i):
thisx = [0,x1[i],x2[i]]
thisy = [0,y1[i],y2[i]]
line.set_data(thisx,thisy)
time_text.set_text(time_template % (i*dt))
return line, time_text
ani = animation.FuncAnimation(fig,animate,np.arange(1,len(y)),interval=25,blit=True,init_func=init)
plt.show()
from numpy import sin, cos
import scipy.integrate as integrate
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.animation import ImageMagickWriter
metadata = dict(title='Darren Movie Test', artist='Matplotlib',
comment='Darren Movie support!')
writer = ImageMagickWriter(fps=15, metadata=metadata)
G = 9.8
L1 = 1.0
L2 = 1.0
M1 = 1.0
M2 = 1.0
def derivs(state,t):
dydx = np.zeros_like(state)
dydx[0] = state[1]
del_ = state[2] - state[0]
den1 = (M1 + M2)*L1 - M2*L1*cos(del_)*cos(del_)
dydx[1] = (M2*L1*state[1]*state[1]*sin(del_)*cos(del_)+ M2*G*sin(state[2])*cos(del_)+M2*L2*state[3]*state[3]*sin(del_)-(M1+M2)*G*sin(state[0]))/den1
dydx[2] = state[3]
den2 = (L2/L1)*den1
dydx[3] = (-M2*L2*state[3]*state[3]*sin(del_)*cos(del_)+ (M1+M2)*G*sin(state[0])*cos(del_) - (M1+M2)*L1*state[1]*state[1]*sin(del_)-(M1+M2)*G*sin(state[2]))/den2
return dydx
dt = 0.05
t = np.arange(0.0,20,dt)
th1 = 120.0
w1 = 0.0
th2 = -10.0
w2 = 0.0
state = np.radians([th1,w1,th2,w2])
y = integrate.odeint(derivs,state,t)
x1 = L1*sin(y[:,0])
y1 = -L1*cos(y[:,0])
x2 = L2*sin(y[:,2]) + x1
y2 = -L2*cos(y[:,2]) + y1
fig = plt.figure()
ax = fig.add_subplot(111,autoscale_on=False,xlim=(-2,2),ylim=(-2,2))
ax.set_aspect('equal')
ax.grid()
line, = ax.plot([],[],'o-',lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05,0.9,'',transform=ax.transAxes)
def init():
line.set_data([],[])
time_text.set_text('')
return line,time_text
def animate(i):
thisx = [0,x1[i],x2[i]]
thisy = [0,y1[i],y2[i]]
line.set_data(thisx,thisy)
time_text.set_text(time_template % (i*dt))
return line, time_text
init()
with writer.saving(fig, "darren_writer_test.gif", 100):
for i in range(300):
animate(i)
writer.grab_frame()
dynamic_image.py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def f(x,y):
return np.sin(x) + np.cos(y)
x = np.linspace(0,2*np.pi,120)
y = np.linspace(0,2*np.pi,100).reshape(-1,1)
ims = []
for i in range(60):
x += np.pi / 15.
y += np.pi / 20.
im = plt.imshow(f(x,y),animated=True)
ims.append([im])
ani = animation.ArtistAnimation(fig,ims,interval=50,blit=True,repeat_delay=1000)
plt.show()
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.animation import ImageMagickWriter
metadata = dict(title='Darren Movie Test', artist='Matplotlib',
comment='Darren Movie support!')
writer = ImageMagickWriter(fps=15, metadata=metadata)
fig = plt.figure()
def f(x,y):
return np.sin(x) + np.cos(y)
x = np.linspace(0,2*np.pi,120)
y = np.linspace(0,2*np.pi,100).reshape(-1,1)
ims = []
for i in range(60):
x += np.pi / 15.
y += np.pi / 20.
im = plt.imshow(f(x,y),animated=True)
ims.append([im])
#ani = animation.ArtistAnimation(fig,ims,interval=50,blit=True,repeat_delay=1000)
#plt.show()
with writer.saving(fig, "darren_writer_test.gif", 100):
for i in range(100):
x += np.pi / 15.
y += np.pi / 20.
im = plt.imshow(f(x,y),animated=True)
ims.append([im])
writer.grab_frame()
rain.py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
np.random.seed(19680801)
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(0, 1), ax.set_xticks([])
ax.set_ylim(0, 1), ax.set_yticks([])
n_drops = 50
rain_drops = np.zeros(n_drops, dtype=[('position', float, 2),
('size', float, 1),
('growth', float, 1),
('color', float, 4)])
rain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))
rain_drops['growth'] = np.random.uniform(50, 200, n_drops)
scat = ax.scatter(rain_drops['position'][:, 0], rain_drops['position'][:, 1],
s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],
facecolors='none')
def update(frame_number):
current_index = frame_number % n_drops
rain_drops['color'][:, 3] -= 1.0/len(rain_drops)
rain_drops['color'][:, 3] = np.clip(rain_drops['color'][:, 3], 0, 1)
rain_drops['size'] += rain_drops['growth']
rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)
rain_drops['size'][current_index] = 5
rain_drops['color'][current_index] = (0, 0, 0, 1)
rain_drops['growth'][current_index] = np.random.uniform(50, 200)
scat.set_edgecolors(rain_drops['color'])
scat.set_sizes(rain_drops['size'])
scat.set_offsets(rain_drops['position'])
animation = FuncAnimation(fig, update, interval=10)
plt.show()
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.animation import ImageMagickWriter
metadata = dict(title='Darren Movie Test', artist='Matplotlib',
comment='Darren Movie support!')
writer = ImageMagickWriter(fps=50, metadata=metadata)
np.random.seed(19680801)
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(0, 1), ax.set_xticks([])
ax.set_ylim(0, 1), ax.set_yticks([])
n_drops = 50
rain_drops = np.zeros(n_drops, dtype=[('position', float, 2),
('size', float, 1),
('growth', float, 1),
('color', float, 4)])
rain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))
rain_drops['growth'] = np.random.uniform(50, 200, n_drops)
scat = ax.scatter(rain_drops['position'][:, 0], rain_drops['position'][:, 1],
s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],
facecolors='none')
def update(frame_number):
current_index = frame_number % n_drops
rain_drops['color'][:, 3] -= 1.0/len(rain_drops)
rain_drops['color'][:, 3] = np.clip(rain_drops['color'][:, 3], 0, 1)
rain_drops['size'] += rain_drops['growth']
rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)
rain_drops['size'][current_index] = 5
rain_drops['color'][current_index] = (0, 0, 0, 1)
rain_drops['growth'][current_index] = np.random.uniform(50, 200)
scat.set_edgecolors(rain_drops['color'])
scat.set_sizes(rain_drops['size'])
scat.set_offsets(rain_drops['position'])
#animation = FuncAnimation(fig, update, interval=10)
#plt.show()
with writer.saving(fig, "darren_writer_test.gif", 100):
for i in range(160):
update(i)
writer.grab_frame()
random_wolk.py
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
np.random.seed(19680801)
def Gen_RandLine(length, dims=2):
lineData = np.empty((dims, length))
lineData[:, 0] = np.random.rand(dims)
for index in range(1, length):
step = ((np.random.rand(dims) - 0.5) * 0.1)
lineData[:, index] = lineData[:, index - 1] + step
return lineData
def update_lines(num, dataLines, lines):
for line, data in zip(lines, dataLines):
line.set_data(data[0:2, :num])
line.set_3d_properties(data[2, :num])
return lines
fig = plt.figure()
ax = p3.Axes3D(fig)
data = [Gen_RandLine(25, 3) for index in range(50)]
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]
ax.set_xlim3d([0.0, 1.0])
ax.set_xlabel('X')
ax.set_ylim3d([0.0, 1.0])
ax.set_ylabel('Y')
ax.set_zlim3d([0.0, 1.0])
ax.set_zlabel('Z')
ax.set_title('3D Test')
line_ani = animation.FuncAnimation(fig, update_lines, 25, fargs=(data, lines),
interval=50, blit=False)
plt.show()
mport numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib.animation import ImageMagickWriter
np.random.seed(19680801)
metadata = dict(title='Darren Movie Test', artist='Matplotlib',
comment='Darren Movie support!')
writer = ImageMagickWriter(fps=15, metadata=metadata)
def Gen_RandLine(length, dims=2):
lineData = np.empty((dims, length))
lineData[:, 0] = np.random.rand(dims)
for index in range(1, length):
step = ((np.random.rand(dims) - 0.5) * 0.1)
lineData[:, index] = lineData[:, index - 1] + step
return lineData
def update_lines(num, dataLines, lines):
for line, data in zip(lines, dataLines):
line.set_data(data[0:2, :num])
line.set_3d_properties(data[2, :num])
return lines
fig = plt.figure()
ax = p3.Axes3D(fig)
#data = [Gen_RandLine(25, 3) for index in range(50)]
data = [Gen_RandLine(25, 3) for index in range(7)]
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]
ax.set_xlim3d([0.0, 1.0])
ax.set_xlabel('X')
ax.set_ylim3d([0.0, 1.0])
ax.set_ylabel('Y')
ax.set_zlim3d([0.0, 1.0])
ax.set_zlabel('Z')
ax.set_title('3D Test')
#line_ani = animation.FuncAnimation(fig, update_lines, 25, fargs=(data, lines),
# interval=50, blit=False)
#plt.show()
with writer.saving(fig, "darren_writer_test.gif", 80):
for i in range(100):
update_lines(i,data,lines)
writer.grab_frame()
hello