{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Blend transparency with color in 2D images\n\nBlend transparency with color to highlight parts of data with imshow.\n\nA common use for `matplotlib.pyplot.imshow` is to plot a 2D statistical\nmap. The function makes it easy to visualize a 2D matrix as an image and add\ntransparency to the output. For example, one can plot a statistic (such as a\nt-statistic) and color the transparency of each pixel according to its p-value.\nThis example demonstrates how you can achieve this effect.\n\nFirst we will generate some data, in this case, we'll create two 2D \"blobs\"\nin a 2D grid. One blob will be positive, and the other negative.\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 normal_pdf(x, mean, var):\n return np.exp(-(x - mean)**2 / (2*var))\n\n\n# Generate the space in which the blobs will live\nxmin, xmax, ymin, ymax = (0, 100, 0, 100)\nn_bins = 100\nxx = np.linspace(xmin, xmax, n_bins)\nyy = np.linspace(ymin, ymax, n_bins)\n\n# Generate the blobs. The range of the values is roughly -.0002 to .0002\nmeans_high = [20, 50]\nmeans_low = [50, 60]\nvar = [150, 200]\n\ngauss_x_high = normal_pdf(xx, means_high[0], var[0])\ngauss_y_high = normal_pdf(yy, means_high[1], var[0])\n\ngauss_x_low = normal_pdf(xx, means_low[0], var[1])\ngauss_y_low = normal_pdf(yy, means_low[1], var[1])\n\nweights = (np.outer(gauss_y_high, gauss_x_high)\n - np.outer(gauss_y_low, gauss_x_low))\n\n# We'll also create a grey background into which the pixels will fade\ngreys = np.full((*weights.shape, 3), 70, dtype=np.uint8)\n\n# First we'll plot these blobs using ``imshow`` without transparency.\nvmax = np.abs(weights).max()\nimshow_kwargs = {\n 'vmax': vmax,\n 'vmin': -vmax,\n 'cmap': 'RdYlBu',\n 'extent': (xmin, xmax, ymin, ymax),\n}\n\nfig, ax = plt.subplots()\nax.imshow(greys)\nax.imshow(weights, **imshow_kwargs)\nax.set_axis_off()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Blending in transparency\n\nThe simplest way to include transparency when plotting data with\n`matplotlib.pyplot.imshow` is to pass an array matching the shape of\nthe data to the ``alpha`` argument. For example, we'll create a gradient\nmoving from left to right below.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Create an alpha channel of linearly increasing values moving to the right.\nalphas = np.ones(weights.shape)\nalphas[:, 30:] = np.linspace(1, 0, 70)\n\n# Create the figure and image\n# Note that the absolute values may be slightly different\nfig, ax = plt.subplots()\nax.imshow(greys)\nax.imshow(weights, alpha=alphas, **imshow_kwargs)\nax.set_axis_off()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using transparency to highlight values with high amplitude\n\nFinally, we'll recreate the same plot, but this time we'll use transparency\nto highlight the extreme values in the data. This is often used to highlight\ndata points with smaller p-values. We'll also add in contour lines to\nhighlight the image values.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Create an alpha channel based on weight values\n# Any value whose absolute value is > .0001 will have zero transparency\nalphas = Normalize(0, .3, clip=True)(np.abs(weights))\nalphas = np.clip(alphas, .4, 1) # alpha value clipped at the bottom at .4\n\n# Create the figure and image\n# Note that the absolute values may be slightly different\nfig, ax = plt.subplots()\nax.imshow(greys)\nax.imshow(weights, alpha=alphas, **imshow_kwargs)\n\n# Add contour lines to further highlight different levels.\nax.contour(weights[::-1], levels=[-.1, .1], colors='k', linestyles='-')\nax.set_axis_off()\nplt.show()\n\nax.contour(weights[::-1], levels=[-.0001, .0001], colors='k', linestyles='-')\nax.set_axis_off()\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. admonition:: References\n\n The use of the following functions, methods, classes and modules is shown\n in this example:\n\n - `matplotlib.axes.Axes.imshow` / `matplotlib.pyplot.imshow`\n - `matplotlib.axes.Axes.contour` / `matplotlib.pyplot.contour`\n - `matplotlib.colors.Normalize`\n - `matplotlib.axes.Axes.set_axis_off`\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 }