{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Ways to set a color's alpha value\n\nCompare setting alpha by the *alpha* keyword argument and by one of the Matplotlib color\nformats. Often, the *alpha* keyword is the only tool needed to add transparency to a\ncolor. In some cases, the *(matplotlib_color, alpha)* color format provides an easy way\nto fine-tune the appearance of a Figure.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\n# Fixing random state for reproducibility.\nnp.random.seed(19680801)\n\nfig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4))\n\nx_values = [n for n in range(20)]\ny_values = np.random.randn(20)\n\nfacecolors = ['green' if y > 0 else 'red' for y in y_values]\nedgecolors = facecolors\n\nax1.bar(x_values, y_values, color=facecolors, edgecolor=edgecolors, alpha=0.5)\nax1.set_title(\"Explicit 'alpha' keyword value\\nshared by all bars and edges\")\n\n\n# Normalize y values to get distinct face alpha values.\nabs_y = [abs(y) for y in y_values]\nface_alphas = [n / max(abs_y) for n in abs_y]\nedge_alphas = [1 - alpha for alpha in face_alphas]\n\ncolors_with_alphas = list(zip(facecolors, face_alphas))\nedgecolors_with_alphas = list(zip(edgecolors, edge_alphas))\n\nax2.bar(x_values, y_values, color=colors_with_alphas,\n edgecolor=edgecolors_with_alphas)\nax2.set_title('Normalized alphas for\\neach bar and each edge')\n\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.bar`\n - `matplotlib.pyplot.subplots`\n\n.. tags::\n\n styling: color\n plot-type: bar\n level: beginner\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 }