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

时间:2017-01-24 17:17:27

标签: python matplotlib jupyter

我希望在将Axes实例添加为PatchCollection之后,切换一个PolygonPatches子集的可见性,但我不确定是否有一种有效的方法可以做到这一点。

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

1 个答案:

答案 0 :(得分:1)

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