python画动态图(gif)
1.散点图gif
%matplotlib notebook
from matplotlib import pyplot as plt
import numpy as np
from matplotlib import animation
plt.rcParams['font.sans-serif'] = ['KaiTi']
plt.rcParams['axes.unicode_minus'] = False
fig = plt.figure(figsize = (14,6))
ax = fig.add_subplot(1, 2, 1)
ax1 = fig.add_subplot(1, 2, 2)
total = 40
x, y = np.random.random((2, total))
z = (x**2 + y**2 >1)
point, = ax.plot([], [] ,'r.')
point2, = ax.plot([], [] , 'b.')
line1, = ax1.plot([], [] , 'red')
ax1.set_xlim(left = 0, right = total)
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax1.set_ylim(bottom =0, top = 5)
x_ = np.array([i/1000 for i in range(1000+1)])
y_ = np.sqrt(1 - x_**2)
ax.plot(x_, y_,'black')
dataInx = []
dataIny = []
dataOutx = []
dataOuty = []
counts = []
piValues = []
def update_point(n, x, y, z, point):
if z[n]:
dataOutx.append(x[n])
dataOuty.append(y[n])
else:
dataInx.append(x[n])
dataIny.append(y[n])
point.set_data(dataInx, dataIny)
point2.set_data(dataOutx, dataOuty)
count = len(dataInx) + len(dataOutx)
piValue = len(dataInx)/(count) * 4
counts.append(count)
piValues.append(piValue)
line1.set_data(counts, piValues)
ax.set_title('蒙特卡洛模拟,次数{:0>3},圆周率估计值{:0<10}'.format(n,round(piValue, 10)),loc = 'center')
ax1.set_title('蒙特卡洛模拟,次数{:0>3},圆周率估计值{:0<10}'.format(n,round(piValue, 10)),loc = 'center')
return point
ani=animation.FuncAnimation(fig, update_point, total,fargs=(x, y, z, point))
ani.save('test1.gif',writer='pillow')
plt.show()

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60

2.三维散点图(gif)
from matplotlib import pyplot as plt
import numpy as np
from matplotlib import animation
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
x = np.random.random(100)
y = np.random.random(100)
z = np.random.random(100)
point, = ax.plot([], [], [], 'r.')
point2, =ax.plot([], [], [], '.')
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.set_zlim([0, 1])
def update_point(n, x, y, z, point):
point2.set_data([x[0:n], y[0:n]])
point2.set_3d_properties(z[0:n], 'z')
point.set_data([x[n], y[n]])
point.set_3d_properties(z[n], 'z')
return point
ani=animation.FuncAnimation(fig, update_point, 99, fargs=(x, y, z, point))
ani.save('test.gif',writer='pillow')
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
