<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>scienceoss.com &#187; ginput</title>
	<atom:link href="http://scienceoss.com/tags/ginput/feed/" rel="self" type="application/rss+xml" />
	<link>http://scienceoss.com</link>
	<description>useful tidbits for using open source software in science</description>
	<lastBuildDate>Wed, 26 May 2010 03:34:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Interactively select points from a plot  in matplotlib</title>
		<link>http://scienceoss.com/interactively-select-points-from-a-plot-in-matplotlib/</link>
		<comments>http://scienceoss.com/interactively-select-points-from-a-plot-in-matplotlib/#comments</comments>
		<pubDate>Mon, 28 Jan 2008 19:30:15 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[matplotlib]]></category>
		<category><![CDATA[plotting]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[ginput]]></category>
		<category><![CDATA[interactive]]></category>
		<category><![CDATA[select points]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=14</guid>
		<description><![CDATA[In Matlab, there is a very useful function called ginput(). There is no such ready-built function for matplotlib/pylab, but all the pieces are there. Copy and paste this code to get ginput functionality. The code is below if you want to jump right to it. Here&#8217;s a little explanation of what&#8217;s happening: The general idea [...]]]></description>
			<content:encoded><![CDATA[<p>In Matlab, there is a very useful function called <span class="c">ginput()</span>.  There is no such ready-built function for matplotlib/pylab, but all the pieces are there.  Copy and paste this code to get ginput functionality.<br />
<span id="more-14"></span><br />
The code is below if you want to jump right to it.</p>
<p>Here&#8217;s a little explanation of what&#8217;s happening:</p>
<p>The general idea is to create a class, the <span class="c">MouseMonitor</span>, that will hold the x and y data coordinates.  This class has a single method, the <span class="c">mycall()</span> method.  <em>Note: you could be tricky and define a <span class="c">__call__</span> method, and save a few keystrokes by just passing <span class="c">mouse</span> (instead of <span class="c">mouse.mycall</span>) to the <span class="c">connect</span> function.  I didn&#8217;t do that here cause it&#8217;s harder to explain.</em></p>
<p>The <span class="c">connect()</span> function needs, as its first argument, the name of an event.  Possible events are &#8216;resize_event&#8217;, &#8216;draw_event&#8217;, &#8216;key_press_event&#8217;, &#8216;key_release_event&#8217;, &#8216;button_press_event&#8217;, &#8216;button_release_event&#8217;, &#8216;motion_notify_event&#8217;, and &#8216;pick_event&#8217;.</p>
<p>The second argument to <span class="c">connect()</span> needs to be the name of a function that will be called every time that event happens.  In this case, it&#8217;s the <span class="c">mycall</span> method of the <span class="c">mouse</span> object, <span class="c">mouse.mycall</span>.</p>
<p>Since mouse.mycall is the callback function given to connect, it will be called every time there is a button press event.  So every time you click on the plot, <span class="c">mouse.mycall</span> it will append the x and y coords to its own internal list, print the x and y coords, plot a red circle, and refresh the plot every time.</p>
<p>When you&#8217;re done, you can access the x and y data in mouse with <span class="c">mouse.xdatalist</span> and <span class="c">mouse.ydatalist</span>.</p>
<p>More examples to follow, but for now here&#8217;s a basic version that improve a little on the functionality of Matlab&#8217;s ginput (which doesn&#8217;t give you graphical feedback on its own).</p>
<pre class = "prettyprint"><code class = "code">
from pylab import *
class MouseMonitor:
    event = None
    xdatalist = []
    ydatalist = []

    def mycall(self, event):
        self.event = event
        self.xdatalist.append(event.xdata)
        self.ydatalist.append(event.ydata)

        print 'x = %s and y = %s' % (event.xdata,event.ydata)

        ax = gca()  # get current axis
        ax.hold(True) # overlay plots.

        # Plot a red circle where you clicked.
        ax.plot([event.xdata],[event.ydata],'ro')

        draw()  # to refresh the plot.

if __name__=="__main__":
    # Example usage
    mouse = MouseMonitor()
    connect('button_press_event', mouse.mycall)
    plot([1,2,3])
    show()
</code></pre>
<h2>An improved version</h2>
<p>The following code allows you to set up a MouseMonitor object that plots multiple sets of data.</p>
<pre class="prettyprint"><code class="code">from pylab import *
import sys
class MouseMonitor:
    event = None
    xdatalist = []
    ydatalist = []

    def my_call(self, event):
        self.event = event

        if event.button == 1:
            self.xdatalist.append(event.xdata)
            self.ydatalist.append(event.ydata)

            sys.stdout.flush()
            print 'x = %s and y = %s' % (event.xdata,event.ydata)
            sys.stdout.flush()
            ax = gca()
            ax.hold(True)
            ax.plot([event.xdata],[event.ydata],'ro')

            draw()

        if event.button == 3:
            disconnect(self.cid)
            self.ask_for_another()

    def ask_for_another(self):
        sys.stdout.flush()
        answer = raw_input('Press n for the next plot, or any other key to stop:  ')
        if answer == 'n':
            self.plot_next()
        else:
            print '::sniff::  bye'
            close('all')

    def set_data(self,x,y):
        self.xlist = x
        self.ylist = y
        self.i = 0

    def plot_next(self):
        if self.i < len(self.xlist):
            cla()
            plot(xlist[self.i],ylist[self.i])
            self.i += 1
            self.connect_to_plot()
            draw()
        else:
            sys.stdout.flush()
            print 'all out of data.'

    def connect_to_plot(self):
        self.cid = connect('button_press_event',self.my_call)

if __name__ == "__main__":
    mouse = MouseMonitor()

    xlist = [[1,2,3],[4,5,6]]
    ylist = [[3,4,5],[8,9,7]]

    mouse.set_data(xlist,ylist)

    mouse.plot_next()

    show()</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/interactively-select-points-from-a-plot-in-matplotlib/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Interacting with figures in Python</title>
		<link>http://scienceoss.com/interacting-with-figures-in-python/</link>
		<comments>http://scienceoss.com/interacting-with-figures-in-python/#comments</comments>
		<pubDate>Thu, 17 Jan 2008 15:09:16 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[matplotlib]]></category>
		<category><![CDATA[plotting]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[ginput]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=62</guid>
		<description><![CDATA[Here is some code from the matplotlib mailing list, sent by Rob Hetland, for selecting points from a plot. from matplotlib.pyplot import * class ginput(object): """docstring for on_click""" def __init__(self): self.x = [] self.y = [] connect('button_press_event', self) def __call__(self, event): xd, yd = event.xdata, event.ydata if event.button==1: if event.inaxes is not None: # print [...]]]></description>
			<content:encoded><![CDATA[<p>Here is some code from the matplotlib mailing list, sent by Rob Hetland, for selecting points from a plot.</p>
<pre class = "prettyprint"><code class = "code">
from matplotlib.pyplot import *

class ginput(object):
    """docstring for on_click"""

    def __init__(self):
        self.x = []
        self.y = []
        connect('button_press_event', self)

    def __call__(self, event):
        xd, yd = event.xdata, event.ydata
        if event.button==1:
            if event.inaxes is not None:
                # print 'data coords', event.xdata, event.ydata
                self.x.append(xd)
                self.y.append(yd)
                plot((xd,), (yd,), 'r+', ms=5)

map_points = ginput()
</code></pre>
<pre class = "prettyprint"><code class = "code">
#!/usr/bin/env python
# encoding: utf-8
"""Polygon geometry.

Copyright (C) 2006, Robert Hetland
Copyright (C) 2006, Stefan van der Walt

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the
   distribution.
3. The name of the author may not be used to endorse or promote
   products derived from this software without specific prior written
   permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""

import numpy as np
import sys

try:
    import scipy.weave as weave

    def npnpoly(verts,points):
        verts = verts.astype(np.float64)
        points = points.astype(np.float64)

        xp = np.ascontiguousarray(verts[:,0])
        yp = np.ascontiguousarray(verts[:,1])
        x = np.ascontiguousarray(points[:,0])
        y = np.ascontiguousarray(points[:,1])
        out = np.empty(len(points),dtype=np.uint8)

        code = """
        /* Code from:

http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html

           Copyright (c) 1970-2003, Wm. Randolph Franklin

           Permission is hereby granted, free of charge, to any person
           obtaining a copy of this software and associated documentation
           files (the "Software"), to deal in the Software without
           restriction, including without limitation the rights to use, copy,
           modify, merge, publish, distribute, sublicense, and/or sell copies
           of the Software, and to permit persons to whom the Software is
           furnished to do so, subject to the following conditions:

        	1. Redistributions of source code must retain the above
                 copyright notice, this list of conditions and the following
                 disclaimers.
        	2. Redistributions in binary form must reproduce the above
                 copyright notice in the documentation and/or other materials
                 provided with the distribution.
        	3. The name of W. Randolph Franklin may not be used to endorse
                 or promote products derived from this Software without
                 specific prior written permission.

           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
           EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
           MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
           NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
           BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
           ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
           CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
           SOFTWARE. */

        int i,j,n;
        unsigned int c;
        int nr_verts = Nxp[0];
        for (n = 0; n < Nx[0]; n++) {
            c = 0;
        	for (i = 0, j = nr_verts-1; i < nr_verts; j = i++) {
                if ((((yp(i)<=y(n)) &#038;&#038; (y(n)<yp(j))) ||
                 	 ((yp(j)<=y(n)) &#038;&#038; (y(n)<yp(i)))) &#038;&#038;
                	(x(n) < (xp(j) - xp(i)) * (y(n) - yp(i)) / (yp(j) - yp(i)) + xp(i)))

    	    	c = !c;
        	}
    	out(n) = c;
        }
        """
        weave.inline(code, ['xp','yp','x','y','out'],
                     type_converters=weave.converters.blitz)
        return out
except:
    # if scipy.weave is not available, use pure python routine.  Slow.
    def npnpoly(verts, points):
        """Check whether given points are in the polygon.

        points - Nx2 array

        See http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
        """
        out = []

        xpi = verts[:,0]
        ypi = verts[:,1]
        # shift
        xpj = xpi[np.arange(xpi.size)-1]
        ypj = ypi[np.arange(ypi.size)-1]
        maybe = np.empty(len(xpi),dtype=bool)
        for x,y in points:
            maybe[:] = ((ypi <= y) &#038; (y < ypj)) | ((ypj <= y) &#038; (y < ypi))
            out.append(sum(x < (xpj[maybe]-xpi[maybe])*(y - ypi[maybe]) \
                           / (ypj[maybe] - ypi[maybe]) + xpi[maybe]) % 2)

        return np.asarray(out,dtype=bool)

class Polygeom(np.ndarray):
    """
    Polygeom -- Polygon geometry class
    """

    def __new__(self, verts):
        """
        Given xp and yp (both 1D arrays or sequences), create a new polygon.

        p = Polygon(vertices) where vertices is an Nx2 array

        p.inside(x, y) - Calculate whether points lie inside the polygon.
        p.area() - The area enclosed by the polygon.
        p.centroid() - The centroid of the polygon
        """
        verts = np.atleast_2d(verts)

        assert verts.shape[1] == 2, 'Vertices should be an Nx2 array, but is %s' % str(verts.shape)
        assert len(verts) >= 3, 'Need 3 vertices to create polygon.'

        # close polygon, if needed
        if not np.all(verts[0]==verts[-1]):
            verts = np.vstack((verts,verts[0]))

        self.verts = verts

        return verts.view(Polygeom).copy()

    def inside(self,points):
        points = np.atleast_2d(points)
        assert points.shape[1] == 2, \
               "Points should be of shape Nx2, is %s" % str(points.shape)
        return npnpoly(self.verts,points).astype(bool)

    def get_area(self):
        """
        Return the area of the polygon.

        From Paul Bourke's webpage:

http://astronomy.swin.edu.au/~pbourke/geometry

        """
        v = self.verts
        v_first = v[:-1][:,[1,0]]
        v_second = v[1:]
        return np.diff(v_first*v_second).sum()/2.0

    def get_centroid(self):
        "Return the centroid of the polygon"
        v = self.verts
        a = np.diff(v[:-1][:,[1,0]]*v[1:])
        area = a.sum()/2.0
        return ((v[:-1,:] + v[1:,:])*a).sum(axis=0) / (6.0*area)

    area = property(get_area)
    centroid = property(get_centroid)

if __name__ == '__main__':
    import pylab as pl
    grid = np.mgrid[0:1:10j,0:1:10j].reshape(2,-1).swapaxes(0,1)

    # simple area test
    verts = np.array([[0.15,0.15],
                      [0.85,0.15],
                      [0.85,0.85],
                      [0.15,0.85]])
    pa = Polygeom(verts)
    print pa.area
    print (0.85-0.15)**2

    print pa

    print pa.centroid

    # concave enclosure test-case for inside.
    verts = np.array([[0.15,0.15],
                      [0.25,0.15],
                      [0.45,0.15],
                      [0.45,0.25],
                      [0.25,0.25],
                      [0.25,0.55],
                      [0.65,0.55],
                      [0.65,0.15],
                      [0.85,0.15],
                      [0.85,0.85],
                      [0.15,0.85]])
    pb = Polygeom(verts)
    inside = pb.inside(grid)
    pl.plot(grid[:,0][inside], grid[:,1][inside], 'g.')
    pl.plot(grid[:,0][~inside], grid[:,1][~inside],'r.')
    pl.plot(pb.verts[:,0],pb.verts[:,1], '-k')
    print pb.centroid
    xc, yc = pb.centroid
    print xc, yc
    pl.plot([xc], [yc], 'co')
    pl.show()

    pl.figure()
    # many points in a semicircle, to test speed.
    grid = np.mgrid[0:1:1000j,0:1:1000j].reshape(2,-1).swapaxes(0,1)
    xp = np.sin(np.arange(0,np.pi,0.01))
    yp = np.cos(np.arange(0,np.pi,0.01))
    pc = Polygeom(np.hstack([xp[:,np.newaxis],yp[:,np.newaxis]]))
    print "%d points inside %d vertex poly..." % (grid.size/2,len(verts)),
    sys.stdout.flush()
    inside = pc.inside(grid)
    print "done."
    pl.plot(grid[:,0][inside], grid[:,1][inside], 'g+')
    pl.plot(grid[:,0][~inside], grid[:,1][~inside], 'r.')
    pl.plot(pc.verts[:,0], pc.verts[:,1], '-k')
    xc, yc = pc.centroid
    print xc, yc
    pl.plot([xc], [yc], 'co')
    pl.show()
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/interacting-with-figures-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

