Skip to main content
 首页 » 编程设计

Python之使用 slider 更改图形图上的文本

2025年02月15日8youxin

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

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

textSlider1 textSlider2

请您参考如下方法:

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

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