如何切换轴上面片子集的可见性

2024-10-03 11:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 实例方法中将子集办法axespatchcollectionpolygonpatches
1条回答
网友
1楼 · 发布于 2024-10-03 11:20:56

那肯定是可能的。您可以直接使用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()

相关问题 更多 >