事件处理matplotlip python
问题描述:
我想从图中选取并绘制点,并在数组中存储它们的坐标。那可能吗?如果是的话,你可以帮助引导我,谢谢你的帮助。事件处理matplotlip python
我有这样的例子,但它是画线:
from matplotlib import pyplot as plt
class LineBuilder:
def __init__(self, line):
self.line = line
self.xs = list(line.get_xdata())
self.ys = list(line.get_ydata())
self.cid = line.figure.canvas.mpl_connect('button_press_event', self)
def __call__(self, event):
print('click', event)
if event.inaxes!=self.line.axes: return
self.xs.append(event.xdata)
self.ys.append(event.ydata)
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click to build line segments')
line, = ax.plot([0], [0]) # empty line
linebuilder = LineBuilder(line)
plt.show()
答
首先,为了吸引点,而不是一条线,你需要定义一个标记,可选择性地开启线断:
line, = ax.plot([0], [0], marker="o", linestyle="")
坐标已存储在阵列LineBuilder.xs
和LineBuilder.xs
中,因此您可以将它们打印出来。
完整的示例:
from matplotlib import pyplot as plt
class LineBuilder:
def __init__(self, line):
self.line = line
self.xs = list(line.get_xdata())
self.ys = list(line.get_ydata())
self.cid = line.figure.canvas.mpl_connect('button_press_event', self)
def __call__(self, event):
if event.inaxes!=self.line.axes: return
self.xs.append(event.xdata)
self.ys.append(event.ydata)
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw_idle()
print(self.xs)
print(self.ys)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click to build line segments')
line, = ax.plot([0], [0], marker="o", linestyle="")
linebuilder = LineBuilder(line)
plt.show()
感谢你,我正在寻找:) –
大,在这种情况下,你可能会[接受](https://meta.stackexchange.com/questions/5234/如何接受答案)答案。您可能还想参加[旅游]了解SO的工作原理。 – ImportanceOfBeingErnest