{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# 2D images in 3D\n\nThis example demonstrates how to plot 2D color coded images (similar to\n`.Axes.imshow`) as a plane in 3D.\n\nMatplotlib does not have a native function for this. Below we build one by relying\non `.Axes3D.plot_surface`. For simplicity, there are some differences to\n`.Axes.imshow`: This function does not set the aspect of the Axes, hence pixels are\nnot necessarily square. Also, pixel edges are on integer values rather than pixel\ncenters. Furthermore, many optional parameters of `.Axes.imshow` are not implemented.\n\nMultiple calls of ``imshow3d`` use independent norms and thus different color scales\nby default. If you want to have a single common color scale, you need to construct\na suitable norm beforehand and pass it to all ``imshow3d`` calls.\n\nA fundamental limitation of the 3D plotting engine is that intersecting objects cannot\nbe drawn correctly. One object will always be drawn after the other. Therefore,\nmultiple image planes can well be used in the background as shown in this example.\nBut this approach is not suitable if the planes intersect.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.colors import Normalize\n\n\ndef imshow3d(ax, array, value_direction='z', pos=0, norm=None, cmap=None):\n \"\"\"\n Display a 2D array as a color-coded 2D image embedded in 3d.\n\n The image will be in a plane perpendicular to the coordinate axis *value_direction*.\n\n Parameters\n ----------\n ax : Axes3D\n The 3D Axes to plot into.\n array : 2D numpy array\n The image values.\n value_direction : {'x', 'y', 'z'}\n The axis normal to the image plane.\n pos : float\n The numeric value on the *value_direction* axis at which the image plane is\n located.\n norm : `~matplotlib.colors.Normalize`, default: Normalize\n The normalization method used to scale scalar data. See `imshow()`.\n cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`\n The Colormap instance or registered colormap name used to map scalar data\n to colors.\n \"\"\"\n if norm is None:\n norm = Normalize()\n colors = plt.get_cmap(cmap)(norm(array))\n\n if value_direction == 'x':\n nz, ny = array.shape\n zi, yi = np.mgrid[0:nz + 1, 0:ny + 1]\n xi = np.full_like(yi, pos)\n elif value_direction == 'y':\n nx, nz = array.shape\n xi, zi = np.mgrid[0:nx + 1, 0:nz + 1]\n yi = np.full_like(zi, pos)\n elif value_direction == 'z':\n ny, nx = array.shape\n yi, xi = np.mgrid[0:ny + 1, 0:nx + 1]\n zi = np.full_like(xi, pos)\n else:\n raise ValueError(f\"Invalid value_direction: {value_direction!r}\")\n ax.plot_surface(xi, yi, zi, rstride=1, cstride=1, facecolors=colors, shade=False)\n\n\nfig = plt.figure()\nax = fig.add_subplot(projection='3d')\nax.set(xlabel=\"x\", ylabel=\"y\", zlabel=\"z\")\n\nnx, ny, nz = 8, 10, 5\ndata_xy = np.arange(ny * nx).reshape(ny, nx) + 15 * np.random.random((ny, nx))\ndata_yz = np.arange(nz * ny).reshape(nz, ny) + 10 * np.random.random((nz, ny))\ndata_zx = np.arange(nx * nz).reshape(nx, nz) + 8 * np.random.random((nx, nz))\n\nimshow3d(ax, data_xy)\nimshow3d(ax, data_yz, value_direction='x', cmap='magma')\nimshow3d(ax, data_zx, value_direction='y', pos=ny, cmap='plasma')\n\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
".. tags::\n plot-type: 3D,\n styling: colormap,\n level: advanced\n\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}