Python+Matplotlib制作动画
程序员文章站
2022-03-01 15:08:08
...
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kun1280437633/article/details/108483384
由于效果gif太大,无法上传,可自行运行 。matplotlib 官网动画例子包含了一部分动画,下面介绍下实例中的动画
demo1:移动的sin曲线
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('seaborn-pastel')
fig = plt.figure()
ax = plt.axes(xlim=(0, 4), ylim=(-2, 2))
line, = ax.plot([], [], lw=3)
def init():
line.set_data([], [])
return line,
def animate(i):
x = np.linspace(0, 4, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
anim = FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)
anim.save('sine_wave.gif', writer='imagemagick')
demo2: 点随着sin函数标记位置
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
# 文本固定位置
# def update_points(num):
# if num % 5 == 0:
# point_ani.set_marker("*")
# point_ani.set_markersize(12)
# else:
# point_ani.set_marker("o")
# point_ani.set_markersize(8)
#
# point_ani.set_data(x[num], y[num])
# text_pt.set_text("x=%.3f, y=%.3f" % (x[num], y[num]))
# return point_ani, text_pt,
# 文本跟着点动
def update_points(num):
point_ani.set_data(x[num], y[num])
if num % 5 == 0:
point_ani.set_marker("*")
point_ani.set_markersize(12)
else:
point_ani.set_marker("o")
point_ani.set_markersize(8)
text_pt.set_position((x[num], y[num]))
text_pt.set_text("x=%.3f, y=%.3f" % (x[num], y[num]))
return point_ani, text_pt,
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
fig = plt.figure(tight_layout=True)
plt.plot(x, y)
point_ani, = plt.plot(x[0], y[0], "ro")
plt.grid(ls="--")
text_pt = plt.text(4, 0.8, '', fontsize=16)
ani = animation.FuncAnimation(fig, update_points, np.arange(0, 100), interval=100, blit=True)
ani.save('sin_test.gif', writer='imagemagick', fps=10)
plt.show()
demo3:示波器上的李萨如图形
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
plt.style.use('dark_background')
fig = plt.figure()
ax = plt.axes(xlim=(-50, 50), ylim=(-50, 50))
line, = ax.plot([], [], lw=2)
# initialization function
def init():
# creating an empty plot/frame
line.set_data([], [])
return line,
# lists to store x and y axis points
xdata, ydata = [], []
#simulate ghost effect of oscilloscope
def ghostImage(x,y):
xdata.append(x)
ydata.append(y)
if len(xdata)>60:
del xdata[0]
del ydata[0]
return xdata,ydata
# animation function
def animate(i):
# t is a parameter
t = i/100.0
# x, y values to be plotted
x = 40*np.sin(2*2*np.pi*(t+0.3))
y = 40*np.cos(3*2*np.pi*t)
# appending new points to x, y axes points list
line.set_data(ghostImage(x,y))
return line,
# setting a title for the plot
plt.title('Creating a Lissajous figure with matplotlib')
# hiding the axis details
plt.axis('off')
# call the animator
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=400, interval=20, blit=True)
# save the animation as gif file
anim.save('figure.gif',writer='imagemagick')
demo4: 散点依次增加,测试点闪烁
import numpy as np
import pandas as pd
from sklearn.feature_selection import SelectKBest,f_classif
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # 空间三维画图
import matplotlib.animation as animation
form = pd.read_excel("./original_file/训练集.xlsx",encoding='GBK') # 两类,各65个
form_1 = pd.read_excel("./original_file/测试集.xlsx",encoding='GBK')
form1 = form.query('label>0')
form2 = form.query("label<1")
form3 = form_1.query("label<1")
# 绘制散点图
fig = plt.figure()
ax = Axes3D(fig)
# 绘制图例
ax.legend(loc='best')
# 添加坐标轴(顺序是Z, Y, X)
ax.set_zlabel('feature map z', fontdict={'color': 'black'})
ax.set_ylabel('feature map y', fontdict={'color': 'black'})
ax.set_xlabel('feature map x', fontdict={'color': 'black'})
def animate(i):
ax.scatter(form1['特征1x'][:i], form1['特征1y'][:i], form1['特征1z'][:i], c='r', label='sick', marker='.')
ax.scatter(form2['特征1x'][:i], form2['特征1y'][:i], form2['特征1z'][:i], c='g', label='healthy', marker='.')
if (i-65) % 2 == 0 and i > 65:
ax.scatter(form3['特征1x'], form3['特征1y'], form3['特征1z'], c='m', label='test', marker='*', s=30)
elif (i-65) % 2 == 1 and i > 65:
ax.scatter(form3['特征1x'], form3['特征1y'], form3['特征1z'], c='y', label='test', marker='*', s=30)
else:
pass
ax.set_title('Location map')
ani = animation.FuncAnimation(fig=fig,
func=animate,
frames=200,
interval=100,
repeat=False,
blit=False)
ani.save('scatter.gif', writer='pillow')
demo5: 三维图画线加旋转
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import animation
fig = plt.figure(1)
ax = fig.add_subplot(1, 1, 1, projection='3d') # 指定三维空间做图
t = np.linspace(0, 4, 200) # 在0到4之间,均匀产生200点的数组
theta = t * 2 * np.pi # 角度
# 生成曲线数组
z = t
x = np.sin(theta)
y = np.cos(theta)
# 运动的点
point, = ax.plot([x[0]], [y[0]], [z[0]], 'ro', label='p')
# 曲线
line, = ax.plot([x[0]], [y[0]], [z[0]], label='line')
# 设置显示的范围和描述
x_min = 0
y_min = 0
z_min = 0
x_max = 1
y_max = 1
z_max = 1
margin = 1
ax.set_xlim(x_min - margin, x_max + margin)
ax.set_ylim(y_min - margin, y_max + margin)
ax.set_zlim(z_min - margin, z_max + margin)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
# 标题
ax.set_title('3D animate')
ax.view_init(30, 35)
# 设置标签在右下角
ax.legend(loc='lower right')
def animate(i):
line.set_xdata(x[:i + 1])
line.set_ydata(y[:i + 1])
line.set_3d_properties(z[:i + 1])
point.set_xdata(x[i])
point.set_ydata(y[i])
point.set_3d_properties(z[i])
ax.view_init(azim=i)
rot_animation = animation.FuncAnimation(fig, animate, frames=np.arange(0,180+2,2),interval=200)
rot_animation.save('line.gif', writer='pillow')
上一篇: 选择排序
下一篇: Java Collections 工具类