How to manage text labels in a simple interactive matplotlib plot?

866 views Asked by At

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

There are 2 answers

4
Josip Juros On

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.

0
Paul Jurczak On

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