{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# MRI with EEG\n\nDisplays a set of subplots with an MRI image, its intensity\nhistogram and some EEG traces.\n\n.. redirect-from:: /gallery/specialty_plots/mri_demo\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib.cbook as cbook\n\nfig, axd = plt.subplot_mosaic(\n [[\"image\", \"density\"],\n [\"EEG\", \"EEG\"]],\n layout=\"constrained\",\n # \"image\" will contain a square image. We fine-tune the width so that\n # there is no excess horizontal or vertical margin around the image.\n width_ratios=[1.05, 2],\n)\n\n# Load the MRI data (256x256 16-bit integers)\nwith cbook.get_sample_data('s1045.ima.gz') as dfile:\n im = np.frombuffer(dfile.read(), np.uint16).reshape((256, 256))\n\n# Plot the MRI image\naxd[\"image\"].imshow(im, cmap=\"gray\")\naxd[\"image\"].axis('off')\n\n# Plot the histogram of MRI intensity\nim = im[im.nonzero()] # Ignore the background\naxd[\"density\"].hist(im, bins=np.arange(0, 2**16+1, 512))\naxd[\"density\"].set(xlabel='Intensity (a.u.)', xlim=(0, 2**16),\n ylabel='MRI density', yticks=[])\naxd[\"density\"].minorticks_on()\n\n# Load the EEG data\nn_samples, n_rows = 800, 4\nwith cbook.get_sample_data('eeg.dat') as eegfile:\n data = np.fromfile(eegfile, dtype=float).reshape((n_samples, n_rows))\nt = 10 * np.arange(n_samples) / n_samples\n\n# Plot the EEG\naxd[\"EEG\"].set_xlabel('Time (s)')\naxd[\"EEG\"].set_xlim(0, 10)\ndy = (data.min() - data.max()) * 0.7 # Crowd them a bit.\naxd[\"EEG\"].set_ylim(-dy, n_rows * dy)\naxd[\"EEG\"].set_yticks([0, dy, 2*dy, 3*dy], labels=['PG3', 'PG5', 'PG7', 'PG9'])\n\nfor i, data_col in enumerate(data.T):\n axd[\"EEG\"].plot(t, data_col + i*dy, color=\"C0\")\n\nplt.show()" ] } ], "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 }