如何对多个多边形使用 set_clip_path()?

How to use set_clip_path() with multiple polygons?

我正在尝试通过 多个多边形 剪辑 点云,但我不知道这是否可行plt.axis.set_clip_path().

因为 set_clip_path() 需要一个 PathPatch 作为参数,你怎么能创建一个由几个多边形组成的几何体?它类似于 plt.MultiPolygon(),但它不存在。我试图用所有的多边形创建一个 matplotlib.PatchCollection,但这不起作用。

这是期望的目标(从上图到下图):

下面是我希望 代码 的样子:

import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
import numpy as np

fig, ax = plt.subplots()

points = np.array([np.random.random(100)*400,
                    np.random.random(100)*100]).T

A = plt.Polygon( np.array([( 0,   0),(50,100),(100,  0)]), color='w', ec='k' )
B = plt.Polygon( np.array([(120 ,  0),(170 , 100), (220,  0)]), color='w', ec='k'  )
C = plt.Polygon( np.array([(240 ,  0),(290 , 100), (340,  0)]), color='w', ec='k'  )

[ax.add_patch(i) for i in (A,B,C)]

ax.scatter(points[:,0], points[:,1], zorder=3).set_clip_path([A,B,C])

您可以连接所有多边形的 verticescodes,并使用它们创建一个 "compound path". Matplotlib's path tutorial 包含仅从一个复合路径创建直方图的示例。

import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import numpy as np

points = np.array([np.random.random(100) * 400,
                   np.random.random(100) * 100]).T
A = plt.Polygon(np.array([(0, 0), (50, 100), (100, 0)]), color='w', ec='k')
B = plt.Polygon(np.array([(120, 0), (170, 100), (220, 0)]), color='w', ec='k')
C = plt.Polygon(np.array([(240, 0), (290, 100), (340, 0)]), color='w', ec='k')

fig, ax = plt.subplots()
all_polys = [A, B, C]
[ax.add_patch(i) for i in all_polys]
vertices = np.concatenate([i.get_path().vertices for i in all_polys])
codes = np.concatenate([i.get_path().codes for i in all_polys])

dots = ax.scatter(points[:, 0], points[:, 1], zorder=3)
dots.set_clip_path(PathPatch(Path(vertices, codes), transform=ax.transData))
plt.show()