gpt4 book ai didi

python - 删除 Canvas 上的点/线 Python Matplotlib

转载 作者:行者123 更新时间:2023-12-01 07:18:40 28 4
gpt4 key购买 nike

我使用以下代码通过鼠标事件在 matplotlib 中绘制线条。每次单击,它们都会保存坐标并绘制线条。

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

是否可以删除相同的行?例如,如果我的点 2 不在正确的位置,那么我想删除完整的线和点。

我该怎么做?

最佳答案

由于您要构建的交互比简单地创建用户单击的点更复杂,因此我建议您使用按钮。

您需要准确定义要实现的操作:删除最后一个点,删除所有点,删除除用于初始化的点之外的所有点...

我将向您展示如何创建一个重置按钮,该按钮将根据 this example 删除所有点。来自 Matplotlib 的文档。

首先,创建一个按钮将填充的 Axes 对象。您需要调整主轴,使两者不重叠。

from matplotlib.widgets import Button

plt.subplots_adjust(bottom=0.2)
breset_ax = plt.axes([0.7, 0.05, 0.1, 0.075])
breset = Button(breset_ax, 'Reset')

然后您将设置按钮的回调。我发现在 LineBuilder 类中定义该回调相关,因为它将清除封装的点。

class LineBuilder:
...

def reset(self, _event):
self.xs = []
self.ys = []
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw_idle()

然后,将该回调绑定(bind)到按钮:

breset.on_clicked(linebuilder.reset)

这会给你类似的东西:

enter image description here

点击重置按钮将删除所有已绘制的点。

<小时/>

完整代码:

from matplotlib import pyplot as plt
from matplotlib.widgets import Button

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)

def reset(self, _event):
self.xs = []
self.ys = []
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw_idle()

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.subplots_adjust(bottom=0.2)
breset_ax = plt.axes([0.7, 0.05, 0.1, 0.075])
breset = Button(breset_ax, 'Reset')
breset.on_clicked(linebuilder.reset)

plt.show()

关于python - 删除 Canvas 上的点/线 Python Matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57817592/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com