动画3D随机游走

动画3D随机游走

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import mpl_toolkits.mplot3d.axes3d as p3
  4. import matplotlib.animation as animation
  5. # Fixing random state for reproducibility
  6. np.random.seed(19680801)
  7. def Gen_RandLine(length, dims=2):
  8. """
  9. Create a line using a random walk algorithm
  10. length is the number of points for the line.
  11. dims is the number of dimensions the line has.
  12. """
  13. lineData = np.empty((dims, length))
  14. lineData[:, 0] = np.random.rand(dims)
  15. for index in range(1, length):
  16. # scaling the random numbers by 0.1 so
  17. # movement is small compared to position.
  18. # subtraction by 0.5 is to change the range to [-0.5, 0.5]
  19. # to allow a line to move backwards.
  20. step = ((np.random.rand(dims) - 0.5) * 0.1)
  21. lineData[:, index] = lineData[:, index - 1] + step
  22. return lineData
  23. def update_lines(num, dataLines, lines):
  24. for line, data in zip(lines, dataLines):
  25. # NOTE: there is no .set_data() for 3 dim data...
  26. line.set_data(data[0:2, :num])
  27. line.set_3d_properties(data[2, :num])
  28. return lines
  29. # Attaching 3D axis to the figure
  30. fig = plt.figure()
  31. ax = p3.Axes3D(fig)
  32. # Fifty lines of random 3-D lines
  33. data = [Gen_RandLine(25, 3) for index in range(50)]
  34. # Creating fifty line objects.
  35. # NOTE: Can't pass empty arrays into 3d version of plot()
  36. lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]
  37. # Setting the axes properties
  38. ax.set_xlim3d([0.0, 1.0])
  39. ax.set_xlabel('X')
  40. ax.set_ylim3d([0.0, 1.0])
  41. ax.set_ylabel('Y')
  42. ax.set_zlim3d([0.0, 1.0])
  43. ax.set_zlabel('Z')
  44. ax.set_title('3D Test')
  45. # Creating the Animation object
  46. line_ani = animation.FuncAnimation(fig, update_lines, 25, fargs=(data, lines),
  47. interval=50, blit=False)
  48. plt.show()

下载这个示例