{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# 3D box surface plot\n\nGiven data on a gridded volume ``X``, ``Y``, ``Z``, this example plots the\ndata values on the volume surfaces.\n\nThe strategy is to select the data from each surface and plot\ncontours separately using `.axes3d.Axes3D.contourf` with appropriate\nparameters *zdir* and *offset*.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\n# Define dimensions\nNx, Ny, Nz = 100, 300, 500\nX, Y, Z = np.meshgrid(np.arange(Nx), np.arange(Ny), -np.arange(Nz))\n\n# Create fake data\ndata = (((X+100)**2 + (Y-20)**2 + 2*Z)/1000+1)\n\nkw = {\n 'vmin': data.min(),\n 'vmax': data.max(),\n 'levels': np.linspace(data.min(), data.max(), 10),\n}\n\n# Create a figure with 3D ax\nfig = plt.figure(figsize=(5, 4))\nax = fig.add_subplot(111, projection='3d')\n\n# Plot contour surfaces\n_ = ax.contourf(\n X[:, :, 0], Y[:, :, 0], data[:, :, 0],\n zdir='z', offset=0, **kw\n)\n_ = ax.contourf(\n X[0, :, :], data[0, :, :], Z[0, :, :],\n zdir='y', offset=0, **kw\n)\nC = ax.contourf(\n data[:, -1, :], Y[:, -1, :], Z[:, -1, :],\n zdir='x', offset=X.max(), **kw\n)\n# --\n\n\n# Set limits of the plot from coord limits\nxmin, xmax = X.min(), X.max()\nymin, ymax = Y.min(), Y.max()\nzmin, zmax = Z.min(), Z.max()\nax.set(xlim=[xmin, xmax], ylim=[ymin, ymax], zlim=[zmin, zmax])\n\n# Plot edges\nedges_kw = dict(color='0.4', linewidth=1, zorder=1e3)\nax.plot([xmax, xmax], [ymin, ymax], 0, **edges_kw)\nax.plot([xmin, xmax], [ymin, ymin], 0, **edges_kw)\nax.plot([xmax, xmax], [ymin, ymin], [zmin, zmax], **edges_kw)\n\n# Set labels and zticks\nax.set(\n xlabel='X [km]',\n ylabel='Y [km]',\n zlabel='Z [m]',\n zticks=[0, -150, -300, -450],\n)\n\n# Set zoom and angle view\nax.view_init(40, -30, 0)\nax.set_box_aspect(None, zoom=0.9)\n\n# Colorbar\nfig.colorbar(C, ax=ax, fraction=0.02, pad=0.1, label='Name [units]')\n\n# Show Figure\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. tags::\n plot-type: 3D,\n level: intermediate\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 }