首页 > 解决方案 > 交互式 python matplolib 小部件在 jupyter notebook 中未按预期更新

问题描述

我正在尝试使 matplotlib 小部件显示来自 1D-numpy 数组的数据,该数组使用可以使用滑块改变的索引从 2D-numpy 数组中提取。

小部件永远不会更新,也不会显示错误消息。我已经确认通过将索引更新为预定义值(与滑块无关)来调用更新方法。

%matplotlib notebook

# This should run on its own in a Jupyter notebook. Interestingly, in this sample-code, the plot does update when the slider is at its maximum, but not otherwise

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons

sampleArray = np.random.rand(5, 100)

fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
ax.set_ylim([0.2, 3])

t = np.arange(0.0, 1.0, 0.01)
s = sampleArray[0]
l, = plt.plot(t, s, lw=2)
ax.margins(x=0)

axcolor = 'lightgoldenrodyellow'
axline = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
#axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)

sline = Slider(axline, 'Line Number', 0, len(sampleArray)-1, valinit=0, valstep=1)
#samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)
x =100

def update(val):
    line_number = sline.val
    l.set_ydata(sampleArray[line_number])
    fig.canvas.draw_idle()





sline.on_changed(update)
#samp.on_changed(update)

resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')


def reset(event):
    sline.reset()
    #samp.reset()
button.on_clicked(reset)

rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)


def colorfunc(label):
    l.set_color(label)
    fig.canvas.draw_idle()
radio.on_clicked(colorfunc)


plt.show()

该图应针对滑块的每一步进行更新。但它只更新滑块的最大值和最小值。

标签: pythonmatplotlibwidgetjupyter

解决方案


我想出了一些。(大多数时候,)的类型sline.val似乎是numpy.float64. 使用round(sline.val.item())代码进行转换后,现在可以按预期工作。


推荐阅读