Pyplot:使用滑动条显示3D数组

4

我有一个三维数组。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

A = np.random.rand(10,5,5)

我希望能够在A中可视化每个5x5的图像。

for Ai in A:
    plt.imshow(Ai)
    plt.show()

除了上面例子中的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()

但是当我使用滑块时,图中的图像没有改变,并且我收到了以下消息

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

我该如何让我的滑块与我的3D数组配合使用?
1个回答

5

事实证明,问题根本不在于滑块,我只需要将滑块返回的值转换为int

替换为

l.set_data(A[int(idx)])

能行/有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接