【发布时间】:2017-06-29 06:51:09
【问题描述】:
我写了以下代码,我希望当我移动滑块时,绘制在图形上的文本相应地改变,这意味着删除以前的文本,并绘制从文本列表中读取的新值,并且能够来回做这个。但是,在滑块上移动一次后,文本会覆盖而不是删除。 我需要有关此问题的帮助,如何在移动滑块时更改打印的文本? 请注意,绘制的正方形的颜色会根据它们的值发生变化,这没有问题。
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()
【问题讨论】:
-
您必须保留对文本字形的引用并在覆盖时将其删除。 stackoverflow.com/a/26006851/1562285