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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patches import Rectangle from matplotlib.text import Text from matplotlib.image import AxesImage import numpy as np from numpy.random import rand
if 1: fig, (ax1, ax2) = plt.subplots(2, 1) ax1.set_title('click on points, rectangles or text', picker=True) ax1.set_ylabel('ylabel', picker=True, bbox=dict(facecolor='red')) line, = ax1.plot(rand(100), 'o', picker=5)
bars = ax2.bar(range(10), rand(10), picker=True) for label in ax2.get_xticklabels(): label.set_picker(True)
def onpick1(event): if isinstance(event.artist, Line2D): thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind print('onpick1 line:', zip(np.take(xdata, ind), np.take(ydata, ind))) elif isinstance(event.artist, Rectangle): patch = event.artist print('onpick1 patch:', patch.get_path()) elif isinstance(event.artist, Text): text = event.artist print('onpick1 text:', text.get_text())
fig.canvas.mpl_connect('pick_event', onpick1)
if 1:
def line_picker(line, mouseevent): """ find the points within a certain distance from the mouseclick in data coords and attach some extra attributes, pickx and picky which are the data points that were picked """ if mouseevent.xdata is None: return False, dict() xdata = line.get_xdata() ydata = line.get_ydata() maxd = 0.05 d = np.sqrt((xdata - mouseevent.xdata)**2. + (ydata - mouseevent.ydata)**2.)
ind = np.nonzero(np.less_equal(d, maxd)) if len(ind): pickx = np.take(xdata, ind) picky = np.take(ydata, ind) props = dict(ind=ind, pickx=pickx, picky=picky) return True, props else: return False, dict()
def onpick2(event): print('onpick2 line:', event.pickx, event.picky)
fig, ax = plt.subplots() ax.set_title('custom picker for line data') line, = ax.plot(rand(100), rand(100), 'o', picker=line_picker) fig.canvas.mpl_connect('pick_event', onpick2)
if 1:
x, y, c, s = rand(4, 100)
def onpick3(event): ind = event.ind print('onpick3 scatter:', ind, np.take(x, ind), np.take(y, ind))
fig, ax = plt.subplots() col = ax.scatter(x, y, 100*s, c, picker=True) fig.canvas.mpl_connect('pick_event', onpick3)
if 1: fig, ax = plt.subplots() im1 = ax.imshow(rand(10, 5), extent=(1, 2, 1, 2), picker=True) im2 = ax.imshow(rand(5, 10), extent=(3, 4, 1, 2), picker=True) im3 = ax.imshow(rand(20, 25), extent=(1, 2, 3, 4), picker=True) im4 = ax.imshow(rand(30, 12), extent=(3, 4, 3, 4), picker=True) ax.axis([0, 5, 0, 5])
def onpick4(event): artist = event.artist if isinstance(artist, AxesImage): im = artist A = im.get_array() print('onpick4 image', A.shape)
fig.canvas.mpl_connect('pick_event', onpick4)
plt.show()
|