Python - 使用滑块更改图形图上的文本

Python - change text on figure plot with slider

我写了下面的代码,我希望当我移动滑块时,绘制在图形上的文本相应地改变,这意味着删除以前的文本,并绘制从文本列表中读取的新值,并被能够来回执行此操作。但是,在滑块上移动一次后,文本会覆盖而不是删除。 我需要有关此问题的帮助,如何在移动滑块时更改绘制的文本? 请注意,绘制方块的颜色会根据它们的值毫无问题地发生变化。

from matplotlib import pyplot
from matplotlib.widgets import Slider
import matplotlib.pyplot as plt
import numpy as np

a = np.random.randint(10, size = 4)
b = np.random.randint(10, size = 4)
c = np.random.randint(10, size = 4)
d = np.random.randint(10, size = 4)

grid = ((a,b),(c,d))
grid = np.array(grid)

fig = plt.figure(figsize=(7,5))
ax = fig.add_subplot(111)
subplots_adjust(left=0.15, bottom=0.25)   

words = ['Sample1', 'Sample2']

data_start = 0.5
dataSlider_ax  = fig.add_axes([0.15, 0.1, 0.7, 0.05])
dataSlider = Slider(dataSlider_ax, 'value', 0, 1, valinit=data_start)

def update(val):
    ref = int(dataSlider.val)    
    print (ref)
    ax.imshow(grid[ref], interpolation ='none', aspect = 'auto')
    for (j,i),label in np.ndenumerate(grid[ref]):    
        text = ax.text(i,j,words[ref])
#        I uncomment the following line, in case I wanted to plot the values of the arrays
#        text = ax.text(i,j,grid[ref][j][i])

dataSlider.on_changed(update)    
pyplot.show()

text 返回的对象使用 set_text 方法。同样,虽然图像看起来变化很好,但实际上您一直在分配越来越多的对象并将它们绘制在彼此之上,并且您可以使用 set_data 以较少的内存分配来更改图像。这是一个修改后的示例(我将滑块值乘以 2,以便在移动滑块时查看任何变化):

from matplotlib import pyplot
from matplotlib.widgets import Slider
import matplotlib.pyplot as plt
import numpy as np

a, b, c, d = [np.random.randint(10, size = 4) for _ in range(4)]
grid = ((a,b),(c,d))
grid = np.array(grid)

fig = plt.figure(figsize=(7,5))
ax = fig.add_subplot(111)
plt.subplots_adjust(left=0.15, bottom=0.25)   

words = ['Sample1', 'Sample2']

data_start = 0.5
dataSlider_ax  = fig.add_axes([0.15, 0.1, 0.7, 0.05])
dataSlider = Slider(dataSlider_ax, 'value', 0, 1, valinit=data_start)

image = ax.imshow(grid[0], interpolation='none', aspect='auto')
texts = [[ax.text(i,j,words[0])
          for i in range(grid.shape[2])]
         for j in range(grid.shape[1])]

def update(val):
    global image, texts
    ref = int(dataSlider.val * 2)    
    print (ref)
    image.set_data(grid[ref])
    for (j,i),label in np.ndenumerate(grid[ref]):
        texts[j][i].set_text(words[ref])
    print(ax.get_children())  # if this list keeps getting longer, you are leaking objects

dataSlider.on_changed(update)    
pyplot.show()