我有一个 3d 数组
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
A = np.random.rand(10,5,5)
Run Code Online (Sandbox Code Playgroud)
我想将每个 5x5 图像可视化A
for Ai in A:
plt.imshow(Ai)
plt.show()
Run Code Online (Sandbox Code Playgroud)
除了像上面的例子那样有 5 个数字之外,我想要一个滑块来在 的第一个坐标的索引之间切换A。
目前,我已尝试以下操作:
idx0 = 3
l = plt.imshow(A[idx0])
axidx = plt.axes([0.25, 0.15, 0.65, 0.03])
slidx = Slider(axidx, 'index', 0, 9, valinit=idx0, valfmt='%d')
def update(val):
idx = slidx.val
l.set_data(A[idx])
fig.canvas.draw_idle()
slidx.on_changed(update)
plt.show()
Run Code Online (Sandbox Code Playgroud)
但是当我使用滑块时,图中的图像不会改变,并且我收到消息
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
Run Code Online (Sandbox Code Playgroud)
如何让滑块与 3d 阵列配合使用?
事实证明,问题根本不在于滑块,我只需要将滑块返回的值转换为int.
替换为
l.set_data(A[int(idx)])
Run Code Online (Sandbox Code Playgroud)
成功了