改变与盒子相交的线条的颜色

与矩形相交的线条用红色着色,而其他线条用蓝色线条留下。此示例展示了intersect_bbox函数。

改变与盒子相交的线条的颜色示例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.transforms import Bbox
  4. from matplotlib.path import Path
  5. # Fixing random state for reproducibility
  6. np.random.seed(19680801)
  7. left, bottom, width, height = (-1, -1, 2, 2)
  8. rect = plt.Rectangle((left, bottom), width, height, facecolor="#aaaaaa")
  9. fig, ax = plt.subplots()
  10. ax.add_patch(rect)
  11. bbox = Bbox.from_bounds(left, bottom, width, height)
  12. for i in range(12):
  13. vertices = (np.random.random((2, 2)) - 0.5) * 6.0
  14. path = Path(vertices)
  15. if path.intersects_bbox(bbox):
  16. color = 'r'
  17. else:
  18. color = 'b'
  19. ax.plot(vertices[:, 0], vertices[:, 1], color=color)
  20. plt.show()

下载这个示例