plot+interaction

John Hunter jdhunter at ace.bsd.uchicago.edu
Mon Apr 12 22:32:02 EDT 2004


>>>>> "Mark" == Mark Alford <alford at wuphys.wustl.edu> writes:

    Mark> I have been using the gnuplot.py package for simple 2D
    Mark> plots.  Works great. But I would like to have a tiny bit of
    Mark> interactivity:

    Mark> I would like the program to know where (in terms of the plot
    Mark> variables x and y) the user has mouse-clicked on the plot
    Mark> window.

    Mark> Is there any other plotting package that offers this
    Mark> functionality?

You can do this in matplotlib, albeit with a little extra work.
matplotlib has different backends, and the way you do this is
dependent on the backend.  Ie, if you are using Tk versus GTK versus
WX the approach is somewhat different, but this will probably be
unified in the near future.

Here is an example showing how to connect mouse move or mouse click to
return the data coordinates of the mouse location using the GTK
backend.


"""
An example of how to interact with the plotting canvas by connecting
to move and click events
"""
import matplotlib
matplotlib.use('GTK')
from matplotlib.matlab import *

t = arange(0.0, 1.0, 0.01)
s = sin(2*pi*t)
ax = subplot(111)
ax.plot(t,s)

canvas = get_current_fig_manager().canvas

def on_move(widget, event):
    # get the x and y coords, flip y from top to bottom
    height = canvas.figure.bbox.y.interval()
    x, y = event.x, height-event.y

    if ax.in_axes(x, y):
        # transData transforms data coords to display coords.  Use the
        # inverse method to transform back
        t = ax.xaxis.transData.inverse_positions(x)
        val = ax.yaxis.transData.inverse_positions(y)
        print t, val

def on_click(widget, event):
    # get the x and y coords, flip y from top to bottom
    height = canvas.figure.bbox.y.interval()
    x, y = event.x, height-event.y
    if event.button==1:
        if ax.in_axes(x, y):
            # transData transforms data coords to display coords.  Use the
            # inverse method to transform back
            t = ax.xaxis.transData.inverse_positions(x)
            val = ax.yaxis.transData.inverse_positions(y)
        
            print t, val


canvas.connect('motion_notify_event', on_move)
canvas.connect('button_press_event', on_click)



show()





More information about the Python-list mailing list