{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Box plots with custom fill colors\n\nTo color each box of a box plot individually:\n\n1) use the keyword argument ``patch_artist=True`` to create filled boxes.\n2) loop through the created boxes and adapt their color.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nnp.random.seed(19680801)\nfruit_weights = [\n np.random.normal(130, 10, size=100),\n np.random.normal(125, 20, size=100),\n np.random.normal(120, 30, size=100),\n]\nlabels = ['peaches', 'oranges', 'tomatoes']\ncolors = ['peachpuff', 'orange', 'tomato']\n\nfig, ax = plt.subplots()\nax.set_ylabel('fruit weight (g)')\n\nbplot = ax.boxplot(fruit_weights,\n patch_artist=True, # fill with color\n tick_labels=labels) # will be used to label x-ticks\n\n# fill with colors\nfor patch, color in zip(bplot['boxes'], colors):\n patch.set_facecolor(color)\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. tags:: styling: color, domain: statistics, plot-type: boxplot\n\n.. 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.boxplot` / `matplotlib.pyplot.boxplot`\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 }