绘制甜甜圈

Draw donuts (miam!) using Paths and PathPatches. This example shows the effect of the path’s orientations in a compound path.

  1. import numpy as np
  2. import matplotlib.path as mpath
  3. import matplotlib.patches as mpatches
  4. import matplotlib.pyplot as plt
  5. def wise(v):
  6. if v == 1:
  7. return "CCW"
  8. else:
  9. return "CW"
  10. def make_circle(r):
  11. t = np.arange(0, np.pi * 2.0, 0.01)
  12. t = t.reshape((len(t), 1))
  13. x = r * np.cos(t)
  14. y = r * np.sin(t)
  15. return np.hstack((x, y))
  16. Path = mpath.Path
  17. fig, ax = plt.subplots()
  18. inside_vertices = make_circle(0.5)
  19. outside_vertices = make_circle(1.0)
  20. codes = np.ones(
  21. len(inside_vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO
  22. codes[0] = mpath.Path.MOVETO
  23. for i, (inside, outside) in enumerate(((1, 1), (1, -1), (-1, 1), (-1, -1))):
  24. # Concatenate the inside and outside subpaths together, changing their
  25. # order as needed
  26. vertices = np.concatenate((outside_vertices[::outside],
  27. inside_vertices[::inside]))
  28. # Shift the path
  29. vertices[:, 0] += i * 2.5
  30. # The codes will be all "LINETO" commands, except for "MOVETO"s at the
  31. # beginning of each subpath
  32. all_codes = np.concatenate((codes, codes))
  33. # Create the Path object
  34. path = mpath.Path(vertices, all_codes)
  35. # Add plot it
  36. patch = mpatches.PathPatch(path, facecolor='#885500', edgecolor='black')
  37. ax.add_patch(patch)
  38. ax.annotate("Outside %s,\nInside %s" % (wise(outside), wise(inside)),
  39. (i * 2.5, -1.5), va="top", ha="center")
  40. ax.set_xlim(-2, 10)
  41. ax.set_ylim(-3, 2)
  42. ax.set_title('Mmm, donuts!')
  43. ax.set_aspect(1.0)
  44. plt.show()

绘制甜甜圈示例

参考

此示例中显示了以下函数,方法,类和模块的使用:

  1. import matplotlib
  2. matplotlib.path
  3. matplotlib.path.Path
  4. matplotlib.patches
  5. matplotlib.patches.PathPatch
  6. matplotlib.patches.Circle
  7. matplotlib.axes.Axes.add_patch
  8. matplotlib.axes.Axes.annotate
  9. matplotlib.axes.Axes.set_aspect
  10. matplotlib.axes.Axes.set_xlim
  11. matplotlib.axes.Axes.set_ylim
  12. matplotlib.axes.Axes.set_title

下载这个示例