生成多边形以填充3D线图

演示如何创建填充线图下空间的多边形。 在这个例子中,多边形是半透明的,产生一种“锯齿状的彩色玻璃”效果。

生成多边形以填充3D线图示例

  1. # This import registers the 3D projection, but is otherwise unused.
  2. from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
  3. from matplotlib.collections import PolyCollection
  4. import matplotlib.pyplot as plt
  5. from matplotlib import colors as mcolors
  6. import numpy as np
  7. # Fixing random state for reproducibility
  8. np.random.seed(19680801)
  9. def cc(arg):
  10. '''
  11. Shorthand to convert 'named' colors to rgba format at 60% opacity.
  12. '''
  13. return mcolors.to_rgba(arg, alpha=0.6)
  14. def polygon_under_graph(xlist, ylist):
  15. '''
  16. Construct the vertex list which defines the polygon filling the space under
  17. the (xlist, ylist) line graph. Assumes the xs are in ascending order.
  18. '''
  19. return [(xlist[0], 0.), *zip(xlist, ylist), (xlist[-1], 0.)]
  20. fig = plt.figure()
  21. ax = fig.gca(projection='3d')
  22. # Make verts a list, verts[i] will be a list of (x,y) pairs defining polygon i
  23. verts = []
  24. # Set up the x sequence
  25. xs = np.linspace(0., 10., 26)
  26. # The ith polygon will appear on the plane y = zs[i]
  27. zs = range(4)
  28. for i in zs:
  29. ys = np.random.rand(len(xs))
  30. verts.append(polygon_under_graph(xs, ys))
  31. poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'), cc('y')])
  32. ax.add_collection3d(poly, zs=zs, zdir='y')
  33. ax.set_xlabel('X')
  34. ax.set_ylabel('Y')
  35. ax.set_zlabel('Z')
  36. ax.set_xlim(0, 10)
  37. ax.set_ylim(-1, 4)
  38. ax.set_zlim(0, 1)
  39. plt.show()

下载这个示例