
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "gallery/lines_bars_and_markers/bar_label_demo.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. meta::
        :keywords: codex

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_gallery_lines_bars_and_markers_bar_label_demo.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_gallery_lines_bars_and_markers_bar_label_demo.py:


=====================
Bar chart with labels
=====================

This example shows how to use the `~.Axes.bar_label` helper function
to create bar chart labels.

See also the :doc:`grouped bar
</gallery/lines_bars_and_markers/barchart>`,
:doc:`stacked bar
</gallery/lines_bars_and_markers/bar_stacked>` and
:doc:`horizontal bar chart
</gallery/lines_bars_and_markers/barh>` examples.

.. GENERATED FROM PYTHON SOURCE LINES 16-20

.. code-block:: Python


    import matplotlib.pyplot as plt
    import numpy as np








.. GENERATED FROM PYTHON SOURCE LINES 21-22

data from https://allisonhorst.github.io/palmerpenguins/

.. GENERATED FROM PYTHON SOURCE LINES 22-45

.. code-block:: Python


    species = ('Adelie', 'Chinstrap', 'Gentoo')
    sex_counts = {
        'Male': np.array([73, 34, 61]),
        'Female': np.array([73, 34, 58]),
    }
    width = 0.6  # the width of the bars: can also be len(x) sequence


    fig, ax = plt.subplots()
    bottom = np.zeros(3)

    for sex, sex_count in sex_counts.items():
        p = ax.bar(species, sex_count, width, label=sex, bottom=bottom)
        bottom += sex_count

        ax.bar_label(p, label_type='center')

    ax.set_title('Number of penguins by sex')
    ax.legend()

    plt.show()




.. image-sg:: /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_001.png
   :alt: Number of penguins by sex
   :srcset: /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_001.png, /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_001_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 46-47

Horizontal bar chart

.. GENERATED FROM PYTHON SOURCE LINES 47-71

.. code-block:: Python


    # Fixing random state for reproducibility
    np.random.seed(19680801)

    # Example data
    people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
    y_pos = np.arange(len(people))
    performance = 3 + 10 * np.random.rand(len(people))
    error = np.random.rand(len(people))

    fig, ax = plt.subplots()

    hbars = ax.barh(y_pos, performance, xerr=error, align='center')
    ax.set_yticks(y_pos, labels=people)
    ax.invert_yaxis()  # labels read top-to-bottom
    ax.set_xlabel('Performance')
    ax.set_title('How fast do you want to go today?')

    # Label with specially formatted floats
    ax.bar_label(hbars, fmt='%.2f')
    ax.set_xlim(right=15)  # adjust xlim to fit labels

    plt.show()




.. image-sg:: /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_002.png
   :alt: How fast do you want to go today?
   :srcset: /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_002.png, /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_002_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 72-73

Some of the more advanced things that one can do with bar labels

.. GENERATED FROM PYTHON SOURCE LINES 73-89

.. code-block:: Python


    fig, ax = plt.subplots()

    hbars = ax.barh(y_pos, performance, xerr=error, align='center')
    ax.set_yticks(y_pos, labels=people)
    ax.invert_yaxis()  # labels read top-to-bottom
    ax.set_xlabel('Performance')
    ax.set_title('How fast do you want to go today?')

    # Label with given captions, custom padding and annotate options
    ax.bar_label(hbars, labels=[f'±{e:.2f}' for e in error],
                 padding=8, color='b', fontsize=14)
    ax.set_xlim(right=16)

    plt.show()




.. image-sg:: /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_003.png
   :alt: How fast do you want to go today?
   :srcset: /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_003.png, /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_003_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 90-91

Bar labels using {}-style format string

.. GENERATED FROM PYTHON SOURCE LINES 91-100

.. code-block:: Python


    fruit_names = ['Coffee', 'Salted Caramel', 'Pistachio']
    fruit_counts = [4000, 2000, 7000]

    fig, ax = plt.subplots()
    bar_container = ax.bar(fruit_names, fruit_counts)
    ax.set(ylabel='pints sold', title='Gelato sales by flavor', ylim=(0, 8000))
    ax.bar_label(bar_container, fmt='{:,.0f}')




.. image-sg:: /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_004.png
   :alt: Gelato sales by flavor
   :srcset: /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_004.png, /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_004_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 101-102

Bar labels using a callable

.. GENERATED FROM PYTHON SOURCE LINES 102-111

.. code-block:: Python


    animal_names = ['Lion', 'Gazelle', 'Cheetah']
    mph_speed = [50, 60, 75]

    fig, ax = plt.subplots()
    bar_container = ax.bar(animal_names, mph_speed)
    ax.set(ylabel='speed in MPH', title='Running speeds', ylim=(0, 80))
    ax.bar_label(bar_container, fmt=lambda x: f'{x * 1.61:.1f} km/h')




.. image-sg:: /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_005.png
   :alt: Running speeds
   :srcset: /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_005.png, /gallery/lines_bars_and_markers/images/sphx_glr_bar_label_demo_005_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 112-126

.. admonition:: References

   The use of the following functions, methods, classes and modules is shown
   in this example:

   - `matplotlib.axes.Axes.bar` / `matplotlib.pyplot.bar`
   - `matplotlib.axes.Axes.barh` / `matplotlib.pyplot.barh`
   - `matplotlib.axes.Axes.bar_label` / `matplotlib.pyplot.bar_label`

.. tags::

   component: label
   plot-type: bar
   level: beginner


.. _sphx_glr_download_gallery_lines_bars_and_markers_bar_label_demo.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: bar_label_demo.ipynb <bar_label_demo.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: bar_label_demo.py <bar_label_demo.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: bar_label_demo.zip <bar_label_demo.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
