使用matplotlib从Python绘图中获取数据,然后保存到数组

时间:2014-11-20 02:02:38

标签: python numpy matplotlib

The first block of code in this answer允许用户生成matplotlib图形,通过单击图形,可以在每次单击后显示图形的x坐标和y坐标。如何将这些坐标保存到5个小数位,比如说,保存为numpy数组(x坐标为X,y坐标为Y?我不确定如何开始这个(这可能是微不足道的),但这里是代码:

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

2 个答案:

答案 0 :(得分:2)

我认为您可以通过使用DataCursor中的列表成员来实现此目的:

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

在通话中,您会将每个事件的X和Y存储到这些成员中:

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

然后你会将此传递给mpl_connect,如下所示:

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

print DC.mouseX, DC.mouseY

我已经在这里说明了原理,但我不明白为什么这也不适用于numpy数组。

答案 1 :(得分:2)

听起来你想要plt.ginput()

作为一个简单的例子:

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

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

plt.show()