{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Grouped bar chart with labels\n\nThis example shows a how to create a grouped bar chart and how to annotate\nbars with labels.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# data from https://allisonhorst.github.io/palmerpenguins/\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nspecies = (\"Adelie\", \"Chinstrap\", \"Gentoo\")\npenguin_means = {\n 'Bill Depth': (18.35, 18.43, 14.98),\n 'Bill Length': (38.79, 48.83, 47.50),\n 'Flipper Length': (189.95, 195.82, 217.19),\n}\n\nx = np.arange(len(species)) # the label locations\nwidth = 0.25 # the width of the bars\nmultiplier = 0\n\nfig, ax = plt.subplots(layout='constrained')\n\nfor attribute, measurement in penguin_means.items():\n offset = width * multiplier\n rects = ax.bar(x + offset, measurement, width, label=attribute)\n ax.bar_label(rects, padding=3)\n multiplier += 1\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_ylabel('Length (mm)')\nax.set_title('Penguin attributes by species')\nax.set_xticks(x + width, species)\nax.legend(loc='upper left', ncols=3)\nax.set_ylim(0, 250)\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` / `matplotlib.pyplot.bar`\n - `matplotlib.axes.Axes.bar_label` / `matplotlib.pyplot.bar_label`\n\n.. tags::\n\n component: label\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 }