Turns out, the problem wasn't with the Slider at all, I just needed to convert the value returned by the slider into an int.

Replacing with

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

does the trick

Answer from usernumber on Stack Overflow
🌐
Matplotlib
matplotlib.org › stable › gallery › mplot3d › imshow3d.html
2D images in 3D — Matplotlib 3.11.1 documentation
But this approach is not suitable if the planes intersect. import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import Normalize def imshow3d(ax, array, value_direction='z', pos=0, norm=None, cmap=None): """ Display a 2D array as a color-coded 2D image embedded in 3d.
Top answer
1 of 2
15

I think your error in the 3D vs 2D surface colour is due to data normalisation in the surface colours. If you normalise the data passed to plot_surface facecolor with, facecolors=plt.cm.BrBG(data/data.max()) the results are closer to what you'd expect.

If you simply want a slice normal to a coordinate axis, instead of using imshow, you could use contourf, which is supported in 3D as of matplotlib 1.1.0,

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from matplotlib import cm

# create a 21 x 21 vertex mesh
xx, yy = np.meshgrid(np.linspace(0,1,21), np.linspace(0,1,21))

# create vertices for a rotated mesh (3D rotation matrix)
X =  xx 
Y =  yy
Z =  10*np.ones(X.shape)

# create some dummy data (20 x 20) for the image
data = np.cos(xx) * np.cos(xx) + np.sin(yy) * np.sin(yy)

# create the figure
fig = plt.figure()

# show the reference image
ax1 = fig.add_subplot(121)
ax1.imshow(data, cmap=plt.cm.BrBG, interpolation='nearest', origin='lower', extent=[0,1,0,1])

# show the 3D rotated projection
ax2 = fig.add_subplot(122, projection='3d')
cset = ax2.contourf(X, Y, data, 100, zdir='z', offset=0.5, cmap=cm.BrBG)

ax2.set_zlim((0.,1.))

plt.colorbar(cset)
plt.show()

This code results in this image:

Although this won't work for a slice at an arbitrary position in 3D where the imshow solution is better.

2 of 2
1

Check out the plotImage function here. You can place the image anywhere and rotate however you need it. Also to not create huge surfaces, you can also downscale the image. Hope this helps!

🌐
Digitales
digitales.com.au › blog › wp-content › uploads › 2021 › 06 › plug-willys-cache › imshow-3d-array-python.html
Imshow 3d array python
Python was created out of the slime and mud left after the great flood. imshow(). mplot 3 d import Axes 3 D Hashes for image_rect-0. tif, into the workspace, and then display it. A black image will have a 3D array with all 0, while a white image will have a 3D array with all 256.
🌐
Terbium
terbium.io › 2017 › 12 › matplotlib-3d
Displaying 3D images in Python - Terbium
December 10, 2017 - With a little trickery, though, we can get nibabel to load the image directly from memory. img.get_data() gets us the 3D data array, and we can get started with plotting!
🌐
Stack Overflow
stackoverflow.com › questions › 71072941 › using-matplotlib-pyplot-imshow-to-display-slices-of-a-3d-array
python - Using matplotlib.pyplot.imshow to display slices of a 3d array - Stack Overflow
February 10, 2022 - I'd recommend using mpl_interactions.hyperslicer - which will automatically generate the slider for you and also works with higher dimensional arrays. mpl-interactions.readthedocs.io/en/stable/examples/… it also integrates with xarray to use coords so that values of the sliders aren't just indices but values. ... You can also use mpl-interactions.ipyplot.imshow mpl-interactions.readthedocs.io/en/stable/examples/imshow.html
🌐
Eso-python
eso-python.github.io › ESOPythonTutorials › ESOPythonDemoDay5_matplotlib_BerndHusemann_part2.html
How to plot 3D data with matplotlib
Since the array to plot is always in units of indices, one should define the extent of the array to tell matplotlib the boundaries of the image in physical units. ... from matplotlib import cm import pyfits hdu = pyfits.open('/scratch/MUSE/NGC2906_test/NGC2906_MUSE_Ha_img.fits') img_Ha = hdu[0].data fig = plt.figure(figsize=(7,5)) ax = fig.add_axes([0.1,0.1,0.88,0.88]) # plot data linearNorm = colors.Normalize(vmin=0.0001,vmax=20.0) logNorm = colors.LogNorm(vmin=0.0001,vmax=20.0) cmap=cm.RdBu_r #img = ax.imshow(img_Ha) img = ax.imshow(img_Ha,origin='lower',interpolation='nearest',cmap=cmap,ext
🌐
scikit-image
scikit-image.org › docs › stable › auto_examples › applications › plot_3d_image_processing.html
Explore 3D images (of cells) — skimage 0.26.0 documentation
We can see that they raise an error when we try to view 3D data: try: fig, ax = plt.subplots() ax.imshow(data, cmap='gray') except TypeError as e: print(str(e))
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › plotting-an-imshow-image-in-3d-in-matplotlib
Plotting an imshow() image in 3d in Matplotlib
August 10, 2021 - Python TechnologiesDatabasesComputer ProgrammingWeb DevelopmentJava TechnologiesComputer ScienceMobile DevelopmentBig Data & AnalyticsMicrosoft TechnologiesDevOpsLatest TechnologiesMachine LearningDigital MarketingSoftware QualityManagement Tutorials View All Categories ... To plot an imshow() image in 3D in Matplotlib, you can display 2D data as both a traditional image and as a 3D surface plot.
🌐
GitHub
gist.github.com › rougier › 9d5655e4d435d6c0e3ec6372ffcd81f8
Matplotlib 3D imshow · GitHub
Matplotlib 3D imshow · Raw · imshow-3d.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters ·
🌐
DataCamp
datacamp.com › tutorial › matplotlib-3d-volumetric-data
Python Matplotlib 3D Visualization with Volumetric Data | DataCamp
April 19, 2017 - It took me just a bit of exploring to find out that imshow returns an AxesImage object, which lives “inside” the matplotlib Axes object where all the drawing takes place, in its .images attribute. And this object provides a convenient set_array method that swaps out the image data being displayed!
🌐
Pydata
xarray.pydata.org › en › v0.16.0 › generated › xarray.DataArray.plot.imshow.html
xarray.DataArray.plot.imshow — xarray 0.15.1 documentation
While other plot methods require the DataArray to be strictly two-dimensional, imshow also accepts a 3D array where some dimension can be interpreted as RGB or RGBA color channels and allows this dimension to be specified via the kwarg rgb=.
🌐
Xarray
docs.xarray.dev › en › stable › generated › xarray.plot.imshow.html
xarray.plot.imshow
While other plot methods require the DataArray to be strictly two-dimensional, imshow also accepts a 3D array where some dimension can be interpreted as RGB or RGBA color channels and allows this dimension to be specified via the kwarg rgb=.
🌐
Xarray
docs.xarray.dev › en › stable › generated › xarray.DataArray.plot.imshow.html
xarray.DataArray.plot.imshow
While other plot methods require the DataArray to be strictly two-dimensional, imshow also accepts a 3D array where some dimension can be interpreted as RGB or RGBA color channels and allows this dimension to be specified via the kwarg rgb=.
🌐
SciPy Lecture Notes
scipy-lectures.org › advanced › image_processing
2.6. Image manipulation and processing using Numpy and Scipy — Scipy lecture notes
>>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='nearest') <matplotlib.image.AxesImage object at 0x...> [Python source code] See also · More interpolation methods are in Matplotlib’s examples. See also · 3-D visualization: Mayavi · See 3D plotting with Mayavi. Image plane widgets · Isosurfaces · … · Images are arrays: use the whole numpy machinery.
🌐
scikit-image
scikit-image.org › docs › dev › auto_examples › applications › plot_3d_image_processing.html
Explore 3D images (of cells) — skimage 0.26.1rc0.dev0 documentation
We can see that they raise an error when we try to view 3D data: try: fig, ax = plt.subplots() ax.imshow(data, cmap='gray') except TypeError as e: print(str(e))
🌐
GeeksforGeeks
geeksforgeeks.org › displaying-3d-images-in-python
Displaying 3D images in Python - GeeksforGeeks
December 19, 2022 - In this example, we use numpy.linspace() that creates an array of 10 linearly placed elements between -1 and 5, both inclusive after that the mesh grid function returns two 2-dimensional arrays, After that in order to visualize an image of 3D wireframe we require passing coordinates of X, Y, Z, color(optional).