0

Lets say you have a plot in matplotlib, something like that:

figure = Figure()
figureCanvas = FigureCanvas(figure)
axes = figure.add_subplot(111)
axes.plot([1, 2, 3], [2, 3, 1], linestyle = "None", marker = "o", color = '#1f77b4', markersize = 3)

This would give you a plot with 3 points. How do I remove a specific point from plot, without redrawing the whole thing again?

1 Answer 1

1

First of all, you need to redraw at least the plot (the Line2D object), otherwise there will be no change in the plot.

Without knowing the purpose of not redrawing, it's hard to judge on an acceptable solution. However, usually you would just redraw the whole canvas. To set new data, the Line2D.set_data() method can be used as shown in the following. You may press the number key (0,1,2) of the point to remove in the plot.

import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [2, 3, 1]

fig, ax = plt.subplots()
line, = ax.plot(x, y, ls="None", marker="o", color='#1f77b4', ms=10)

def remove_point(event):
    try:
        key = int(event.key)
        xvals = x[:]
        xvals.pop(key)
        yvals = y[:]
        yvals.pop(key)
        line.set_data(xvals,yvals)
        fig.canvas.draw_idle()
    except:
        pass

fig.canvas.mpl_connect('key_press_event', remove_point)
ax.set_title("Press number of point to remove")
plt.show()
Sign up to request clarification or add additional context in comments.

2 Comments

Your solution worked for me and I'm fine with that, but it still feels a little odd to just replace all the data with set_data function. Is there good way to not replace data in line, but update it? Maybe you can remove point by index, like line.remove(index)
What exactly is the difference between "replacing" and "updating"? Internally a new numpy array needs to be created in both cases, so there is no gain in doing it differently.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.