smilingbuddha
smilingbuddha

Reputation: 14660

Getting matplotlib to render points clicked with a mouse.

I am new to Gui programming, so if this question has been repeated elsewhere using proper terminology I apologize. Is it possible to make interactive geometric animations with matplotlib? In particular, I want to embed an interactive Matplotlib window within a Tkinter frame to test out several variants of the same algorithm.

Here is a typical usage scenario for which I want to write an interactive program as described above: Say I want to test a triangulation algorithm for point-sets in the 2-d plane.

When I run my new_triangulation_algorithm.py script, I would like to open up an interactive tkinter frame having an embedded matplotlib window, where the user "mouses-in" his/her points by clicking on, say, 20 different points -- every time a point is selected, a thick blue dot appears at that position. I know Matplotlib "knows" the coordinates of the point when I hover my mouse cursor over it since I always see it displayed in the status bar of my plots.

But I don't know how to input a point at that position with a mouse.

The second panel of my Tkinter frame would then contain several buttons, each button corresponding a different triangulation algorithm which I would like to animate on a given point set.

As the algorithm proceeds, I would like the matplotlib window to get refreshed to show the current state of the algorithm. I presume I would have to use Matplotlib's animation feature to do this, but I am not sure about this since Matplotlib will have to be embedded in a Tkinter frame.

In future, I would like not only to input points, but also segments, circles, rectangles, but I would want to master a basic example with points as described above.

Upvotes: 3

Views: 1448

Answers (1)

Niemerds
Niemerds

Reputation: 942

This example might be a start. Its backend independend. To add your own buttons you might want to have a look at matplotlibs NavigationToolbar class. There are backend specific implementations like NavigationToolbar2QTAgg. You could inherit the Tk version and add some controls.

from matplotlib import pyplot
import numpy

x_pts = []
y_pts = []

fig, ax = pyplot.subplots()

line, = ax.plot(x_pts, y_pts, marker="o")

def onpick(event):
    m_x, m_y = event.x, event.y
    x, y = ax.transData.inverted().transform([m_x, m_y])
    x_pts.append(x)
    y_pts.append(y)
    line.set_xdata(x_pts)
    line.set_ydata(y_pts)
    fig.canvas.draw()

fig.canvas.mpl_connect('button_press_event', onpick)

pyplot.show()

Upvotes: 3

Related Questions