Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlibs ginput() with undefined number of points

I need to define an area in a plot(s) using the matplotlib function ginput(). However since it is an irregular shape and will be different in each plot so I cant define how many points there will be before hand, i.e.

x = randn(10,10)
imshow(x)
n = I don't know yet
points = ginput(n)

Anyone know how to go about this?? thanks Dave

like image 235
Dave Avatar asked Jun 06 '12 17:06

Dave


1 Answers

From the docs, i.e. help(ginput),

ginput(self, n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2)

Blocking call to interact with the figure.

This will wait for n clicks from the user and return a list of the coordinates of each click.

If timeout is zero or negative, does not timeout.

If n is zero or negative, accumulate clicks until a middle click (or potentially both mouse buttons at once) terminates the input.

Right clicking cancels last input.

The buttons used for the various actions (adding points, removing points, terminating the inputs) can be overriden via the arguments *mouse_add*, *mouse_pop* and *mouse_stop*, that give the associated mouse button: 1 for left, 2 for middle, 3 for right.

The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. The delete and backspace keys act like right clicking (i.e., remove last point), the enter key terminates input and any other key (not already used by the window manager) selects a point.

We can set n=0 to have ginput wait for a mouse middle click instead of a set number of points.

Bonus: setting timeout=0 stops ginput from quitting after the default 30s. I find this annoying for complex plots.

Example code:

import pylab
x = randn(10,10)
imshow(x)
points = ginput(0, 0)
# Select the points defining your region from the
# plot then middle click to terminate ginput.
like image 134
aaren Avatar answered Nov 14 '22 21:11

aaren