{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Bar chart with labels\n\nThis example shows how to use the `~.Axes.bar_label` helper function\nto create bar chart labels.\n\nSee also the :doc:`grouped bar\n</gallery/lines_bars_and_markers/barchart>`,\n:doc:`stacked bar\n</gallery/lines_bars_and_markers/bar_stacked>` and\n:doc:`horizontal bar chart\n</gallery/lines_bars_and_markers/barh>` examples.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "data from https://allisonhorst.github.io/palmerpenguins/\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "species = ('Adelie', 'Chinstrap', 'Gentoo')\nsex_counts = {\n    'Male': np.array([73, 34, 61]),\n    'Female': np.array([73, 34, 58]),\n}\nwidth = 0.6  # the width of the bars: can also be len(x) sequence\n\n\nfig, ax = plt.subplots()\nbottom = np.zeros(3)\n\nfor sex, sex_count in sex_counts.items():\n    p = ax.bar(species, sex_count, width, label=sex, bottom=bottom)\n    bottom += sex_count\n\n    ax.bar_label(p, label_type='center')\n\nax.set_title('Number of penguins by sex')\nax.legend()\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Horizontal bar chart\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n# Example data\npeople = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')\ny_pos = np.arange(len(people))\nperformance = 3 + 10 * np.random.rand(len(people))\nerror = np.random.rand(len(people))\n\nfig, ax = plt.subplots()\n\nhbars = ax.barh(y_pos, performance, xerr=error, align='center')\nax.set_yticks(y_pos, labels=people)\nax.invert_yaxis()  # labels read top-to-bottom\nax.set_xlabel('Performance')\nax.set_title('How fast do you want to go today?')\n\n# Label with specially formatted floats\nax.bar_label(hbars, fmt='%.2f')\nax.set_xlim(right=15)  # adjust xlim to fit labels\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Some of the more advanced things that one can do with bar labels\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots()\n\nhbars = ax.barh(y_pos, performance, xerr=error, align='center')\nax.set_yticks(y_pos, labels=people)\nax.invert_yaxis()  # labels read top-to-bottom\nax.set_xlabel('Performance')\nax.set_title('How fast do you want to go today?')\n\n# Label with given captions, custom padding and annotate options\nax.bar_label(hbars, labels=[f'\u00b1{e:.2f}' for e in error],\n             padding=8, color='b', fontsize=14)\nax.set_xlim(right=16)\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Bar labels using {}-style format string\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fruit_names = ['Coffee', 'Salted Caramel', 'Pistachio']\nfruit_counts = [4000, 2000, 7000]\n\nfig, ax = plt.subplots()\nbar_container = ax.bar(fruit_names, fruit_counts)\nax.set(ylabel='pints sold', title='Gelato sales by flavor', ylim=(0, 8000))\nax.bar_label(bar_container, fmt='{:,.0f}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Bar labels using a callable\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "animal_names = ['Lion', 'Gazelle', 'Cheetah']\nmph_speed = [50, 60, 75]\n\nfig, ax = plt.subplots()\nbar_container = ax.bar(animal_names, mph_speed)\nax.set(ylabel='speed in MPH', title='Running speeds', ylim=(0, 80))\nax.bar_label(bar_container, fmt=lambda x: f'{x * 1.61:.1f} km/h')"
      ]
    },
    {
      "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.barh` / `matplotlib.pyplot.barh`\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.14.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}