流图

流图或流线图用于显示2D矢量场。此示例显示了 streamplot() 函数的一些功能:

  • 沿着流线改变颜色。
  • 改变流线的密度。
  • 沿流线改变线宽。
  • 控制流线的起点。
  • 流线跳过蒙面区域和NaN值。
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.gridspec as gridspec
  4. w = 3
  5. Y, X = np.mgrid[-w:w:100j, -w:w:100j]
  6. U = -1 - X**2 + Y
  7. V = 1 + X - Y**2
  8. speed = np.sqrt(U*U + V*V)
  9. fig = plt.figure(figsize=(7, 9))
  10. gs = gridspec.GridSpec(nrows=3, ncols=2, height_ratios=[1, 1, 2])
  11. # Varying density along a streamline
  12. ax0 = fig.add_subplot(gs[0, 0])
  13. ax0.streamplot(X, Y, U, V, density=[0.5, 1])
  14. ax0.set_title('Varying Density')
  15. # Varying color along a streamline
  16. ax1 = fig.add_subplot(gs[0, 1])
  17. strm = ax1.streamplot(X, Y, U, V, color=U, linewidth=2, cmap='autumn')
  18. fig.colorbar(strm.lines)
  19. ax1.set_title('Varying Color')
  20. # Varying line width along a streamline
  21. ax2 = fig.add_subplot(gs[1, 0])
  22. lw = 5*speed / speed.max()
  23. ax2.streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw)
  24. ax2.set_title('Varying Line Width')
  25. # Controlling the starting points of the streamlines
  26. seed_points = np.array([[-2, -1, 0, 1, 2, -1], [-2, -1, 0, 1, 2, 2]])
  27. ax3 = fig.add_subplot(gs[1, 1])
  28. strm = ax3.streamplot(X, Y, U, V, color=U, linewidth=2,
  29. cmap='autumn', start_points=seed_points.T)
  30. fig.colorbar(strm.lines)
  31. ax3.set_title('Controlling Starting Points')
  32. # Displaying the starting points with blue symbols.
  33. ax3.plot(seed_points[0], seed_points[1], 'bo')
  34. ax3.axis((-w, w, -w, w))
  35. # Create a mask
  36. mask = np.zeros(U.shape, dtype=bool)
  37. mask[40:60, 40:60] = True
  38. U[:20, :20] = np.nan
  39. U = np.ma.array(U, mask=mask)
  40. ax4 = fig.add_subplot(gs[2:, :])
  41. ax4.streamplot(X, Y, U, V, color='r')
  42. ax4.set_title('Streamplot with Masking')
  43. ax4.imshow(~mask, extent=(-w, w, -w, w), alpha=0.5,
  44. interpolation='nearest', cmap='gray', aspect='auto')
  45. ax4.set_aspect('equal')
  46. plt.tight_layout()
  47. plt.show()

流图示例

参考

下面的示例演示了以下函数和方法的使用:

  1. import matplotlib
  2. matplotlib.axes.Axes.streamplot
  3. matplotlib.pyplot.streamplot
  4. matplotlib.gridspec
  5. matplotlib.gridspec.GridSpec
  6. Total running time of the script: ( 0 minutes 1.403 seconds)

下载这个示例