【问题标题】:Python - change text on figure plot with sliderPython - 使用滑块更改图形上的文本
【发布时间】: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()

【问题讨论】:

标签: python text plot figure


【解决方案1】:

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

【讨论】:

  • @感谢您的回答 Jouni。我不知道这在 StackOverflow 上是否合适,询问同一主题中的更多细节,但我试图使用 tkinter 应用它,但 image 没有更新。这怎么能用tkinter来实现?
猜你喜欢
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
相关资源
最近更新 更多