{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Discrete distribution as horizontal bar chart\n\nStacked bar charts can be used to visualize discrete distributions.\n\nThis example visualizes the result of a survey in which people could rate\ntheir agreement to questions on a five-element scale.\n\nThe horizontal stacking is achieved by calling `~.Axes.barh()` for each\ncategory and passing the starting point as the cumulative sum of the\nalready drawn bars via the parameter ``left``.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\ncategory_names = ['Strongly disagree', 'Disagree',\n 'Neither agree nor disagree', 'Agree', 'Strongly agree']\nresults = {\n 'Question 1': [10, 15, 17, 32, 26],\n 'Question 2': [26, 22, 29, 10, 13],\n 'Question 3': [35, 37, 7, 2, 19],\n 'Question 4': [32, 11, 9, 15, 33],\n 'Question 5': [21, 29, 5, 5, 40],\n 'Question 6': [8, 19, 5, 30, 38]\n}\n\n\ndef survey(results, category_names):\n \"\"\"\n Parameters\n ----------\n results : dict\n A mapping from question labels to a list of answers per category.\n It is assumed all lists contain the same number of entries and that\n it matches the length of *category_names*.\n category_names : list of str\n The category labels.\n \"\"\"\n labels = list(results.keys())\n data = np.array(list(results.values()))\n data_cum = data.cumsum(axis=1)\n category_colors = plt.colormaps['RdYlGn'](\n np.linspace(0.15, 0.85, data.shape[1]))\n\n fig, ax = plt.subplots(figsize=(9.2, 5))\n ax.invert_yaxis()\n ax.xaxis.set_visible(False)\n ax.set_xlim(0, np.sum(data, axis=1).max())\n\n for i, (colname, color) in enumerate(zip(category_names, category_colors)):\n widths = data[:, i]\n starts = data_cum[:, i] - widths\n rects = ax.barh(labels, widths, left=starts, height=0.5,\n label=colname, color=color)\n\n r, g, b, _ = color\n text_color = 'white' if r * g * b < 0.5 else 'darkgrey'\n ax.bar_label(rects, label_type='center', color=text_color)\n ax.legend(ncols=len(category_names), bbox_to_anchor=(0, 1),\n loc='lower left', fontsize='small')\n\n return fig, ax\n\n\nsurvey(results, category_names)\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.barh` / `matplotlib.pyplot.barh`\n - `matplotlib.axes.Axes.bar_label` / `matplotlib.pyplot.bar_label`\n - `matplotlib.axes.Axes.legend` / `matplotlib.pyplot.legend`\n\n.. tags::\n\n domain: statistics\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.5" } }, "nbformat": 4, "nbformat_minor": 0 }