.. only:: html
.. note::
:class: sphx-glr-download-link-note
Click :ref:`here ` to download the full example code
.. rst-class:: sphx-glr-example-title
.. _sphx_glr_gallery_lines_bars_and_markers_categorical_variables.py:
==============================
Plotting categorical variables
==============================
How to use categorical variables in Matplotlib.
Many times you want to create a plot that uses categorical variables
in Matplotlib. Matplotlib allows you to pass categorical variables directly to
many plotting functions, which we demonstrate below.
.. code-block:: default
import matplotlib.pyplot as plt
data = {'apple': 10, 'orange': 15, 'lemon': 5, 'lime': 20}
names = list(data.keys())
values = list(data.values())
fig, axs = plt.subplots(1, 3, figsize=(9, 3), sharey=True)
axs[0].bar(names, values)
axs[1].scatter(names, values)
axs[2].plot(names, values)
fig.suptitle('Categorical Plotting')
.. image:: /gallery/lines_bars_and_markers/images/sphx_glr_categorical_variables_001.png
:alt: Categorical Plotting
:class: sphx-glr-single-img
.. rst-class:: sphx-glr-script-out
Out:
.. code-block:: none
Text(0.5, 0.98, 'Categorical Plotting')
This works on both axes:
.. code-block:: default
cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing", "washing"]
fig, ax = plt.subplots()
ax.plot(activity, dog, label="dog")
ax.plot(activity, cat, label="cat")
ax.legend()
plt.show()
.. image:: /gallery/lines_bars_and_markers/images/sphx_glr_categorical_variables_002.png
:alt: categorical variables
:class: sphx-glr-single-img
.. _sphx_glr_download_gallery_lines_bars_and_markers_categorical_variables.py:
.. only :: html
.. container:: sphx-glr-footer
:class: sphx-glr-footer-example
.. container:: sphx-glr-download sphx-glr-download-python
:download:`Download Python source code: categorical_variables.py `
.. container:: sphx-glr-download sphx-glr-download-jupyter
:download:`Download Jupyter notebook: categorical_variables.ipynb `
.. only:: html
.. rst-class:: sphx-glr-signature
Keywords: matplotlib code example, codex, python plot, pyplot
`Gallery generated by Sphinx-Gallery
`_