照貓畫虎,首先看看Python matpotlib官網http://matplotlib.org/examples/index.html上的樣本都完成了什麼功能,畢竟自己研究API太費時
1、
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.animation as animationdef data_gen(t=0): cnt = 0 while cnt < 1000: cnt += 1 t += 0.1 yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)def init(): ax.set_ylim(-1.1, 1.1) ax.set_xlim(0, 10) del xdata[:] del ydata[:] line.set_data(xdata, ydata) return line,fig, ax = plt.subplots()line, = ax.plot([], [], lw=2)ax.grid()xdata, ydata = [], []def run(data): # update the data t, y = data 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) return line,ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10, repeat=False, init_func=init)plt.show()
2、
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.animation as animationfig = 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)im = plt.imshow(f(x, y), animated=True)def updatefig(*args): global x, y x += np.pi / 15. y += np.pi / 20. im.set_array(f(x, y)) return im,ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)plt.show()
3、
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.animation as animationdef update_line(num, data, line): line.set_data(data[..., :num]) return line,fig1 = plt.figure()data = np.random.rand(2, 25)l, = plt.plot([], [], 'r-')plt.xlim(0, 1)plt.ylim(0, 1)plt.xlabel('x')plt.title('test')line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l), interval=50, blit=True)# To save the animation, use the command: line_ani.save('lines.mp4')fig2 = plt.figure()x = np.arange(-9, 10)y = np.arange(-9, 10).reshape(-1, 1)base = np.hypot(x, y)ims = []for add in np.arange(15): ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000, blit=True)# To save this second animation with some metadata, use the following command:# im_ani.save('im.mp4', metadata={'artist':'Guido'})plt.show()
4、
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.patches as patchesimport matplotlib.path as pathimport matplotlib.animation as animationfig, ax = plt.subplots()# histogram our data with numpydata = np.random.randn(1000)n, bins = np.histogram(data, 100)# get the corners of the rectangles for the histogramleft = np.array(bins[:-1])right = np.array(bins[1:])bottom = np.zeros(len(left))top = bottom + nnrects = len(left)# here comes the tricky part -- we have to set up the vertex and path# codes arrays using moveto, lineto and closepoly# for each rect: 1 for the MOVETO, 3 for the LINETO, 1 for the# CLOSEPOLY; the vert for the closepoly is ignored but we still need# it to keep the codes aligned with the verticesnverts = nrects*(1 + 3 + 1)verts = np.zeros((nverts, 2))codes = np.ones(nverts, int) * path.Path.LINETOcodes[0::5] = path.Path.MOVETOcodes[4::5] = path.Path.CLOSEPOLYverts[0::5, 0] = leftverts[0::5, 1] = bottomverts[1::5, 0] = leftverts[1::5, 1] = topverts[2::5, 0] = rightverts[2::5, 1] = topverts[3::5, 0] = rightverts[3::5, 1] = bottombarpath = 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())def animate(i): # simulate new data coming in 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, ]ani = animation.FuncAnimation(fig, animate, 100, repeat=False, blit=True)plt.show()
5、將動畫儲存視頻檔案,先安裝 sudo apt -get install ffmpeg
import numpy as npimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltimport matplotlib.animation as animationdef update_line(num, data, line): line.set_data(data[..., :num]) return line,# Set up formatting for the movie filesWriter = animation.writers['ffmpeg']writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)fig1 = plt.figure()data = np.random.rand(2, 25)l, = plt.plot([], [], 'r-')plt.xlim(0, 1)plt.ylim(0, 1)plt.xlabel('x')plt.title('test')line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l), interval=50, blit=True)FFwriter = animation.FFMpegWriter()line_ani.save('basic_animation.mp4', writer = FFwriter, fps=30, extra_args=['-vcodec', 'libx264'])#line_ani.save('lines.mp4', writer=writer)fig2 = plt.figure()x = np.arange(-9, 10)y = np.arange(-9, 10).reshape(-1, 1)base = np.hypot(x, y)ims = []for add in np.arange(15): ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000, blit=True)#im_ani.save('im.mp4', writer=writer)