使用matplotlib从Python绘图中获取数据,然后保存到数组
允许用户生成matplotlib图形,通过单击图形,可以在每次单击后显示图形的x坐标和y坐标。如何将这些坐标保存到小数点后5位,例如,保存到numpy数组中(使用matplotlib从Python绘图中获取数据,然后保存到数组,python,numpy,matplotlib,Python,Numpy,Matplotlib,允许用户生成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:
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()
我认为您可以通过使用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\u connect
:
DC = DataCursor(plt.gca())
fig.canvas.mpl_connect('pick_event', DC)
...
print DC.mouseX, DC.mouseY
我已经在这里说明了原理,但我不明白为什么这不能应用于numpy阵列。我认为您可以通过使用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\u connect
:
DC = DataCursor(plt.gca())
fig.canvas.mpl_connect('pick_event', DC)
...
print DC.mouseX, DC.mouseY
我已经在这里说明了原理,但我不明白为什么这不能应用于numpy阵列。听起来像是你想要的
举个简单的例子:
fig, ax = plt.subplots()
ax.plot(range(10), 'ro-')
points = plt.ginput(n=4)
print points
np.savetxt('yourfilename', points)
plt.show()
听起来像是你想要的
举个简单的例子:
fig, ax = plt.subplots()
ax.plot(range(10), 'ro-')
points = plt.ginput(n=4)
print points
np.savetxt('yourfilename', points)
plt.show()