如何切换轴中补丁子集的可见性

How to toggle visibility of a subset of patches in an axes

我想在 Axes 实例中切换 PolygonPatches 子集的可见性,在将它们添加为 PatchCollection 之后,但我不确定是否有有效的方法来做到这一点。

有没有办法从 Axes 实例中获取补丁的子集,然后切换它们的可见性?

当然可以。您可以直接使用 PatchCollection.set_visible() 来显示和隐藏 PatchCollection。

然后,使用 Button 切换可见性。

import numpy as np
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from matplotlib.widgets import Button
import matplotlib.pyplot as plt

patches = []
for i in range(3):
    polygon = Polygon(np.random.rand(3, 2), True)
    patches.append(polygon)

colors = 100*np.random.rand(len(patches))
p = PatchCollection(patches, alpha=0.4)
p.set_array(np.array(colors))

fig, ax = plt.subplots()
ax.add_collection(p)

bax = fig.add_axes([0.45,0.91,0.1,0.05])
button = Button(bax, "toggle")

def update(event):
    p.set_visible(not p.get_visible())
    fig.canvas.draw_idle()

button.on_clicked(update)

plt.show()