雨模拟

通过设置50个散点的比例和不透明度来模拟表面上的雨滴。

作者:Nicolas P. Rougier

雨模拟示例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.animation import FuncAnimation
  4. # Fixing random state for reproducibility
  5. np.random.seed(19680801)
  6. # Create new Figure and an Axes which fills it.
  7. fig = plt.figure(figsize=(7, 7))
  8. ax = fig.add_axes([0, 0, 1, 1], frameon=False)
  9. ax.set_xlim(0, 1), ax.set_xticks([])
  10. ax.set_ylim(0, 1), ax.set_yticks([])
  11. # Create rain data
  12. n_drops = 50
  13. rain_drops = np.zeros(n_drops, dtype=[('position', float, 2),
  14. ('size', float, 1),
  15. ('growth', float, 1),
  16. ('color', float, 4)])
  17. # Initialize the raindrops in random positions and with
  18. # random growth rates.
  19. rain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))
  20. rain_drops['growth'] = np.random.uniform(50, 200, n_drops)
  21. # Construct the scatter which we will update during animation
  22. # as the raindrops develop.
  23. scat = ax.scatter(rain_drops['position'][:, 0], rain_drops['position'][:, 1],
  24. s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],
  25. facecolors='none')
  26. def update(frame_number):
  27. # Get an index which we can use to re-spawn the oldest raindrop.
  28. current_index = frame_number % n_drops
  29. # Make all colors more transparent as time progresses.
  30. rain_drops['color'][:, 3] -= 1.0/len(rain_drops)
  31. rain_drops['color'][:, 3] = np.clip(rain_drops['color'][:, 3], 0, 1)
  32. # Make all circles bigger.
  33. rain_drops['size'] += rain_drops['growth']
  34. # Pick a new position for oldest rain drop, resetting its size,
  35. # color and growth factor.
  36. rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)
  37. rain_drops['size'][current_index] = 5
  38. rain_drops['color'][current_index] = (0, 0, 0, 1)
  39. rain_drops['growth'][current_index] = np.random.uniform(50, 200)
  40. # Update the scatter collection, with the new colors, sizes and positions.
  41. scat.set_edgecolors(rain_drops['color'])
  42. scat.set_sizes(rain_drops['size'])
  43. scat.set_offsets(rain_drops['position'])
  44. # Construct the animation, using the update function as the animation director.
  45. animation = FuncAnimation(fig, update, interval=10)
  46. plt.show()

下载这个示例