{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Plotting categorical variables\n\nYou can pass categorical values (i.e. strings) directly as x- or y-values to\nmany plotting functions:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n\ndata = {'apple': 10, 'orange': 15, 'lemon': 5, 'lime': 20}\nnames = list(data.keys())\nvalues = list(data.values())\n\nfig, axs = plt.subplots(1, 3, figsize=(9, 3), sharey=True)\naxs[0].bar(names, values)\naxs[1].scatter(names, values)\naxs[2].plot(names, values)\nfig.suptitle('Categorical Plotting')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Categorical values are a mapping from names to positions. This means that\nvalues that occur multiple times are mapped to the same position. See the\n``cat`` and ``dog`` values \"happy\" and \"bored\" on the y-axis in the following\nexample.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"cat = [\"bored\", \"happy\", \"bored\", \"bored\", \"happy\", \"bored\"]\ndog = [\"happy\", \"happy\", \"happy\", \"happy\", \"bored\", \"bored\"]\nactivity = [\"combing\", \"drinking\", \"feeding\", \"napping\", \"playing\", \"washing\"]\n\nfig, ax = plt.subplots()\nax.plot(activity, dog, label=\"dog\")\nax.plot(activity, cat, label=\"cat\")\nax.legend()\n\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
".. tags::\n\n plot-type: specialty\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
}