Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

The first block of code in this answer allows the user to generate a matplotlib figure and by clicking on the graph, it is possible to display the x- and y- coordinates of the graph after each click. How can I save these coordinates to 5 decimal places, say, into a numpy array (X for the x-coordinates and Y for the y-coordinates)? I'm not really sure how to start this (and it's probably trivial), but here is the code:

import numpy as np
import matplotlib.pyplot as plt


X = []
Y = []

class DataCursor(object):
    text_template = 'x: %0.2f\ny: %0.2f'
    x, y = 0.0, 0.0
    xoffset, yoffset = -20, 20
    text_template = 'x: %0.2f\ny: %0.2f'

    def __init__(self, ax):
        self.ax = ax
        self.annotation = ax.annotate(self.text_template, 
                xy=(self.x, self.y), xytext=(self.xoffset, self.yoffset), 
                textcoords='offset points', ha='right', va='bottom',
                bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
                arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')
                )
        self.annotation.set_visible(False)

    def __call__(self, event):
        self.event = event
        self.x, self.y = event.mouseevent.xdata, event.mouseevent.ydata
        if self.x is not None:
            self.annotation.xy = self.x, self.y
            self.annotation.set_text(self.text_template % (self.x, self.y))
            self.annotation.set_visible(True)
            event.canvas.draw()

fig = plt.figure()
line, = plt.plot(range(10), 'ro-')
fig.canvas.mpl_connect('pick_event', DataCursor(plt.gca()))
line.set_picker(5) # Tolerance in points

plt.show()
share|improve this question

2 Answers 2

up vote 2 down vote accepted

It sounds like you want plt.ginput().

As a quick example:

fig, ax = plt.subplots()
ax.plot(range(10), 'ro-')

points = plt.ginput(n=4)
print points
np.savetxt('yourfilename', points)

plt.show()
share|improve this answer

I think you can do this by using list members in DataCursor:

def __init__(self, ax):
    ...
    self.mouseX = []
    self.mouseY = []

In your call, you would then store the X and Y for each event into these members:

def __call__(self, event):
    ...
    self.mouseX.append(self.x)
    self.mouseY.append(self.y)

You would then pass this to mpl_connect like this:

DC = DataCursor(plt.gca())
fig.canvas.mpl_connect('pick_event', DC)
...

print DC.mouseX, DC.mouseY

I have illustrated the principle here, but I don't see why this couldn't be applied to numpy arrays as well.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.