Medulla Oblongata
Medulla Oblongata

Reputation: 3961

Get data from Python plot with matplotlib then save to array

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()

Upvotes: 1

Views: 1626

Answers (2)

Joe Kington
Joe Kington

Reputation: 284602

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()

Upvotes: 2

vikramls
vikramls

Reputation: 1822

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.

Upvotes: 2

Related Questions