File: dynamic_collection.py

package info (click to toggle)
matplotlib 0.98.1-1%2Blenny4
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 18,624 kB
  • ctags: 22,599
  • sloc: python: 76,915; cpp: 63,459; ansic: 5,353; makefile: 111; sh: 12
file content (48 lines) | stat: -rw-r--r-- 1,191 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import random
from matplotlib.collections import RegularPolyCollection
import matplotlib.cm as cm
from matplotlib.pyplot import figure, show
from numpy.random import rand

fig = figure()
ax = fig.add_subplot(111, xlim=(0,1), ylim=(0,1), autoscale_on=False)
ax.set_title("Press 'a' to add a point, 'd' to delete one")
# a single point
offsets = [(0.5,0.5)]
facecolors = [cm.jet(0.5)]

collection = RegularPolyCollection(
    #fig.dpi,
    5, # a pentagon
    rotation=0,
    sizes=(50,),
    facecolors = facecolors,
    edgecolors = 'black',
    linewidths = (1,),
    offsets = offsets,
    transOffset = ax.transData,
    )

ax.add_collection(collection)

def onpress(event):
    """
    press 'a' to add a random point from the collection, 'd' to delete one
    """
    if event.key=='a':
        x,y = rand(2)
        color = cm.jet(rand())
        offsets.append((x,y))
        facecolors.append(color)
        fig.canvas.draw()
    elif event.key=='d':
        N = len(offsets)
        if N>0:
            ind = random.randint(0,N-1)
            offsets.pop(ind)
            facecolors.pop(ind)
            fig.canvas.draw()

fig.canvas.mpl_connect('key_press_event', onpress)

show()