多三角三维曲面

使用三角形网格绘制曲面的另外两个示例。

第一个演示使用plot_trisurf的三角形参数,第二个设置Triangulation对象的蒙版并将对象直接传递给plot_trisurf。

多三角三维曲面示例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.tri as mtri
  4. # This import registers the 3D projection, but is otherwise unused.
  5. from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
  6. fig = plt.figure(figsize=plt.figaspect(0.5))
  7. #============
  8. # First plot
  9. #============
  10. # Make a mesh in the space of parameterisation variables u and v
  11. u = np.linspace(0, 2.0 * np.pi, endpoint=True, num=50)
  12. v = np.linspace(-0.5, 0.5, endpoint=True, num=10)
  13. u, v = np.meshgrid(u, v)
  14. u, v = u.flatten(), v.flatten()
  15. # This is the Mobius mapping, taking a u, v pair and returning an x, y, z
  16. # triple
  17. x = (1 + 0.5 * v * np.cos(u / 2.0)) * np.cos(u)
  18. y = (1 + 0.5 * v * np.cos(u / 2.0)) * np.sin(u)
  19. z = 0.5 * v * np.sin(u / 2.0)
  20. # Triangulate parameter space to determine the triangles
  21. tri = mtri.Triangulation(u, v)
  22. # Plot the surface. The triangles in parameter space determine which x, y, z
  23. # points are connected by an edge.
  24. ax = fig.add_subplot(1, 2, 1, projection='3d')
  25. ax.plot_trisurf(x, y, z, triangles=tri.triangles, cmap=plt.cm.Spectral)
  26. ax.set_zlim(-1, 1)
  27. #============
  28. # Second plot
  29. #============
  30. # Make parameter spaces radii and angles.
  31. n_angles = 36
  32. n_radii = 8
  33. min_radius = 0.25
  34. radii = np.linspace(min_radius, 0.95, n_radii)
  35. angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
  36. angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
  37. angles[:, 1::2] += np.pi/n_angles
  38. # Map radius, angle pairs to x, y, z points.
  39. x = (radii*np.cos(angles)).flatten()
  40. y = (radii*np.sin(angles)).flatten()
  41. z = (np.cos(radii)*np.cos(3*angles)).flatten()
  42. # Create the Triangulation; no triangles so Delaunay triangulation created.
  43. triang = mtri.Triangulation(x, y)
  44. # Mask off unwanted triangles.
  45. xmid = x[triang.triangles].mean(axis=1)
  46. ymid = y[triang.triangles].mean(axis=1)
  47. mask = np.where(xmid**2 + ymid**2 < min_radius**2, 1, 0)
  48. triang.set_mask(mask)
  49. # Plot the surface.
  50. ax = fig.add_subplot(1, 2, 2, projection='3d')
  51. ax.plot_trisurf(triang, z, cmap=plt.cm.CMRmap)
  52. plt.show()

下载这个示例