0

In this code snippet:

import matplotlib.pyplot as plt
import numpy as np

def onclick(event):
  plt.text(event.xdata, event.ydata, f'x', color='black')
  plt.show()

fig, ax = plt.subplots()
fig.canvas.mpl_connect('button_press_event', onclick)
data = np.random.rand(8, 8)
plt.imshow(data, origin='lower', interpolation='None', aspect='equal')
plt.axis('off')
plt.show()

each mouse click leaves an additional letter x on top of the image:

enter image description here

I would like to have only the most recent x shown. How to accomplish it, while keeping it simple?

2 Answers 2

1

I would recommend you declare a global variable called "txt" or something, and then on click you would first remove the "current" x and add the new one.

txt = None

def onclick(event):
    global txt
    if txt:
        txt.remove()
    txt = plt.text(event.xdata, event.ydata, 'TESTTEST', fontsize=8)
    fig.canvas.draw()

Something like this. It may be messy, But try it.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. It works after a correction: if txt: txt.remove(). The first fig.canvas.draw() is not necessary.
@PaulJurczak Nice, Glad to be of help :)
Do you know, by the chance, how to remove all text added to the plot with one matplotlib function call? What is the data structure holding references to the text?
@PaulJurczak If I remember correctly doing plot.texts should return a List or Tuple of all texts on the plot.
0

The text objects are stored internally by matplotlib. The ones created by plt.text() can be removed. Here is the original code snippet, modified to accomplish this:

import matplotlib.pyplot as plt
import matplotlib.text as text
import numpy as np

def onclick(event):
  for x in plt.findobj(match=text.Text):
    try:
      x.remove()
    except NotImplementedError:
      pass

  plt.text(event.xdata, event.ydata, f'x', color='black')
  plt.show()

fig, ax = plt.subplots()
fig.canvas.mpl_connect('button_press_event', onclick)
data = np.random.rand(8, 8)
plt.imshow(data, origin='lower', interpolation='None', aspect='equal')
plt.axis('off')
plt.show()

Comments

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.