# Python使用matplotlib创建Gif动图的思路

## 1、Matplotlib 简介

Matplotlib的命令式 API，通常过于冗长。

## 2、绘制动画正弦和余弦波

```import matplotlib.animation as anime
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

fig = plt.figure()
l, = plt.plot([], [], 'k-')
l2, = plt.plot([], [], 'm--')
p1, = plt.plot([], [], 'ko')
p2, = plt.plot([], [], 'mo')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.title('title')
plt.xlim(-5, 5)
plt.ylim(-5, 5)
def func(x):
return np.sin(x) * 3
def func2(x):
return np.cos(x) * 3
xlist = []
ylist = []
ylist2 = []
xlist2 = []
with writer.saving(fig, "sin+cosinewave.gif", 100):
for xval in np.linspace(-5, 5, 100):
xlist.append(xval)
ylist.append(func(xval))
l.set_data(xlist, ylist)
l2.set_data(xlist2, ylist2)
p1.set_data(xval, func(xval))
writer.grab_frame()
xlist2.append(xval)
ylist2.append(func2(xval))
p2.set_data(xval, func2(xval))```

## 3、绘制曲面图

```import matplotlib
from matplotlib import cm
import matplotlib.animation as anime
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(29680801)
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
plt.xlim(-5, 5)
plt.ylim(-5, 5)
def func(x, y, r, t):
return np.cos(r / 2 + t) * np.exp(-np.square(r) / 50)
xdata = np.linspace(-10, 10, 1000)
ydata = np.linspace(-10, 10, 1000)
x_list, y_list = np.meshgrid(xdata, ydata)
r_list = np.sqrt(np.square(x_list) + np.square(y_list))
with writer.saving(fig, "exp3d.gif", 100):
for t in np.linspace(0, 20, 160):
z = func(x_list, y_list, r_list, t)
ax.set_zlim(-1, 1)
ax.plot_surface(x_list, y_list, z, cmap=cm.viridis)
writer.grab_frame()
plt.cla()```

## 4、绘制回归图

```import matplotlib
from matplotlib import cm
import matplotlib.animation as anime
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(23680545)
fig = plt.figure()
plt.xlim(-8, 8)
plt.ylim(-8, 8)
def func(x):
return x * 1.2 + 0.1 + np.random.normal(0, 2, x.shape)
x = np.random.uniform(-7, 7, 10)
x = np.sort(x)
y = func(x)
coeff = np.polyfit(x, y, 1)
print(coeff)
xline = np.linspace(-6, 6, 40)
yline = np.polyval(coeff, xline)
lPnt, = plt.plot(x, y, 'o')
l, = plt.plot(xline, yline, 'k-', linewidth=3)
plt.show()
fig = plt.figure()
plt.xlim(-10, 10)
plt.ylim(-10, 10)
lPnt, = plt.plot([], [], 'o')
l, = plt.plot([], [], 'k-', linewidth=3)
x_List = []
y_List = []
x_pnt = []
y_pnt = []
with writer.saving(fig, "fitPlot.gif", 100):
for xval, yval in zip(x, y):
x_pnt.append(xval)
y_pnt.append(yval)
lPnt.set_data(x_pnt, y_pnt)
l.set_data(x_List, y_List)
writer.grab_frame()
writer.grab_frame()
for x_val, y_val in zip(xline, xline):
x_List.append(x_val)
y_List.append(y_val)
lPnt.set_data(x_pnt, y_pnt)
l.set_data(x_List, y_List)
writer.grab_frame()
for i in range(10):
writer.grab_frame()```