Thursday, July 19, 2012

How to click at specific locations on a plot and use x,y coords?

I want to add some interactive fitting to my plotting.  Specifically, I want to click at a position, have the code fit a gaussian there, and overplot the result.  You would think this is easy to find, right?  No.  It took me 30 min of walking down blind alleys in the matplotlib documentation.  But let's cut to the chase.

The answer is:  Event connections.

I stole the example code in the above link, cleaned it up, and adapted it to my 4-panel figure:

def onclick(event):  # Print x,y location where I clicked
    print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
        event.button, event.x, event.y, event.xdata, event.ydata)
for j in range(0,Nfigs):
    fig    = pylab.figure(num=j+1, figsize=plotsize)  #from matplotlib
    for i in range(0, Npanels/Nfigs):
          blagh blagh plot each panel of the figure.
    fig.canvas.mpl_connect('button_press_event', onclick)  #monitor each figure for a click



That really should NOT have taken so long to figure out.  Grr.  But thanks to the great Adam of pyspeckit fame for setting me on the right path!



Here is the red herring I pursued first: matplotlib.widgets,  Maybe this will be good for something else later...


Simple examples of how to use matplotlib's widgets.  (I've copied them locally to ~/Python/Matplotlib-examples.)  Let's work through them.


slider_demo.py:  Ooh, shiny!  I can interactively change the amplitude, frequency, and color of a sine curve.  What's amazing is how terse the code is -- only 43 lines!


radio_buttons.py is also useful.


span_selector.py does what I want, but all the functionality is hidden


BTW, there's a nomenclature difference from other languages: the Cursor widget just shows where the cursor is.  It tracks your movements, but does NOT appear to grab the value.


1 comment:

  1. btw, there are sliders in pyspeckit... but I've found them to be a bit painful to work with (it's a bit challenging to determine what limits are acceptable for, e.g., amplitude)

    ReplyDelete