python - 交互式 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()
该图应针对滑块的每一步进行更新。但它只更新滑块的最大值和最小值。
解决方案
我想出了一些。(大多数时候,)的类型sline.val
似乎是numpy.float64
. 使用round(sline.val.item())
代码进行转换后,现在可以按预期工作。
推荐阅读
- matplotlib - 如何在matplotlib中更改底部x轴顶部的一些x轴刻度标签的位置?
- c# - 未看到主 aspx 文件副本中的更改
- wordpress - 如何创建一个页面,客户可以在其中使用 WordPress 创建自己的自定义产品
- mysql - 如何在 Liquibase 中使用组合 PK 表编写更新语句
- vb.net - 为什么我不能将此变量分配给可为空的?(Visual Basic)
- python - pandas groupby-aggregate 中动态创建字段名
- javascript - React-Redux 为什么我的代码没有从状态中删除项目?
- python - Django 模板 - 我想将换行符呈现为 \n 而不是
- sql-server - 客户端如何通过 SQL Server 解密 AES 加密文件
- idl-programming-language - IDL lambda:尝试下标超出范围