[英]Interactive python matplolib widget doesn't update as expected in jupyter notebook
I am trying to make a matplotlib widget show data from a 1D-numpy array that is extracted from a 2D-numpy array using an index that can be varied using a slider.我正在尝试使 matplotlib 小部件显示来自 1D-numpy 数组的数据,该数组是从 2D-numpy 数组中提取的,使用可以使用滑块改变的索引。
The widget never updates and no error message is displayed.小部件永远不会更新,也不会显示错误消息。 I have confirmed that the update-method is called by updating the index to a predifined value (which is not related to the slider).我已经确认通过将索引更新为预定义值(与滑块无关)来调用更新方法。
%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()
The plot should update for every step of the slider.该图应为滑块的每一步更新。 But it only updates at the maximum and the minimum value of the slider.但它只在滑块的最大值和最小值处更新。
I figured some of it out.我想出了一些。 (Most of the time,) the type of sline.val
seems to be numpy.float64
. (大多数情况下,) sline.val
的类型似乎是numpy.float64
。 After converting this using round(sline.val.item())
the code now works as expected.使用round(sline.val.item())
转换后,代码现在按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.