2017-01-24 65 views
0

我想在Axes實例中將PolygonPatches的子集的可見性切換爲PatchCollection,但我不確定是否有效方法來做到這一點。如何切換軸中補丁子集的可見性

是否有方法從Axes實例獲取修補程序的子集,然後切換其可見性?

回答

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()