一步一步教你用 Matplotlib 保存 GIF 动图

·  阅读 8009

1. 绘制基本动图

1.1 重置重绘

• 导入基本库
``````import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

• 生成数据，画出原始图
``````fig, ax = plt.subplots()

x = np.arange(0, 2 * np.pi, 0.01)
line0 = ax.plot(x, np.cos(x))
line, = ax.plot(x, np.sin(x))

• 定义初始函数和跟新函数
``````def init():
line.set_ydata(np.sin(x))
return line,

def animate(i):
line.set_ydata(np.sin(x + i / 10.0))
return line,

• 执行动画
``````animation = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init, interval=20, blit=False)

• 保存
``````animation.save('resetvalue.gif', writer='imagemagick')

• 显示动图
``````plt.show()

1.2 擦除重绘

• 导入基本库
``````import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

• 生成数据，画出原始图
``````fig, ax = plt.subplots()

x = np.arange(0, 2 * np.pi, 0.01)
ax.plot(x, np.cos(x))

• 定义初始函数和跟新函数
``````def init():
return ax.plot(x, np.sin(x))

def animate(i):
try:
ax.lines.pop(1)
except Exception:
pass
line = ax.plot(x, np.sin(x + i / 10.0), 'r')
return line,

• 后续
``````animation = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init, interval=20, blit=False)
animation.save('redraw.gif', writer='imagemagick')
plt.show()

2. 机器学习过程可视化

``````# coding: utf-8
from __future__ import print_function
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.interpolate import spline

train_X = np.linspace(0, 10, 50)
noise = np.random.normal(0, 1, train_X.shape)
train_Y = train_X * 1 - 2 + noise

X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)

W = tf.Variable(-1., name="weight")
b = tf.Variable(1., name="bias")

learning_rate = 0.0001

cost = tf.reduce_sum(tf.pow(activation - Y, 2))

training_epochs = 20
display_step = 10

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(training_epochs):
for (x, y) in zip(train_X, train_Y):
sess.run(optimizer, feed_dict={X: x, Y: y})
if epoch < 10 or epoch % display_step == 0:
c_tmp = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
W_tmp = sess.run(W)
b_tmp = sess.run(b)
activation_tmp = sess.run(activation, feed_dict={X: train_X})
print("Epoch: %04d" % (epoch + 1), "cost=", "{:.9f}".format(c_tmp), "W=", W_tmp, "b=", b_tmp)
print("Optimization Finished!")
print("cost=", sess.run(cost, feed_dict={X: train_X, Y: train_Y}), "W=", sess.run(W), "b=", sess.run(b))

``````c_trace = []
W_trace = []
b_trace = []
activation_trace = []

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(training_epochs):
for (x, y) in zip(train_X, train_Y):
sess.run(optimizer, feed_dict={X: x, Y: y})
if epoch < 10 or epoch % display_step == 0:
c_tmp = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
W_tmp = sess.run(W)
b_tmp = sess.run(b)
activation_tmp = sess.run(activation, feed_dict={X: train_X})
print("Epoch: %04d" % (epoch + 1), "cost=", "{:.9f}".format(c_tmp), "W=", W_tmp, "b=", b_tmp)
c_trace.append(c_tmp)
W_trace.append(W_tmp)
b_trace.append(b_tmp)
activation_trace.append(activation_tmp)
print("Optimization Finished!")
print("cost=", sess.run(cost, feed_dict={X: train_X, Y: train_Y}), "W=", sess.run(W), "b=", sess.run(b))

``````fig, ax = plt.subplots()
l1 = ax.scatter(train_X, train_Y, color='red', label=r'\$Original\ data\$')
ax.set_xlabel(r'\$X\ data\$')
ax.set_ylabel(r'\$Y\ data\$')

def update(i):
try:
ax.lines.pop(0)
except Exception:
pass
line, = ax.plot(train_X, activation_trace[i], 'g--', label=r'\$Fitting\ line\$', lw=2)
return line,

ani = animation.FuncAnimation(fig, update, frames=len(activation_trace), interval=100)
ani.save('linearregression.gif', writer='imagemagick')

plt.show()

``````def update(i):
try:
ax.lines.pop(0)
except Exception:
pass
line, = ax.plot(train_X, activation_trace[i], 'g--', label=r'\$Fitting\ line\$', lw=2)
if i == len(activation_trace) - 1:
twinax = ax.twinx()
twinax.plot(np.linspace(0, 10, np.size(c_trace)), c_trace, 'b', label='Cost line', lw=2)
return line,

``````def update(i):
try:
ax.lines.pop(0)
except Exception:
pass
line, = ax.plot(train_X, activation_trace[i], 'g--', label=r'\$Fitting\ line\$', lw=2)
if i == len(activation_trace) - 1:
xnew = np.linspace(0, 10, np.max(c_trace) - np.min(c_trace))
smooth = spline(np.linspace(0, 10, np.size(c_trace)), c_trace, xnew)
twinax = ax.twinx()
twinax.set_ylabel(r'Cost')
twinax.plot(xnew, smooth, 'b', label=r'\$Cost\ line\$', lw=2)
return line,

``````def update(i):
try:
ax.lines.pop(0)
except Exception:
pass
line, = ax.plot(train_X, activation_trace[i], 'g--', label=r'\$Fitting\ line\$', lw=2)
plt.legend(handles=[l1, line], loc='upper center')
if i == len(activation_trace) - 1:
ax.text(6, -2, 'Cost: %s' % c_trace[i], fontdict={'size': 16, 'color': 'r'})
xnew = np.linspace(0, 10, np.max(c_trace) - np.min(c_trace))
smooth = spline(np.linspace(0, 10, np.size(c_trace)), c_trace, xnew)
twinax = ax.twinx()
twinax.set_ylabel(r'Cost')
costline, = twinax.plot(xnew, smooth, 'b', label=r'\$Cost\ line\$', lw=2)
plt.legend(handles=[l1, line, costline], loc='upper center')
return line,

``````learning_rate = 0.001

training_epochs = 500
display_step = 40