{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Hat graph\nThis example shows how to create a `hat graph`_ and how to annotate it with\nlabels.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef hat_graph(ax, xlabels, values, group_labels):\n \"\"\"\n Create a hat graph.\n\n Parameters\n ----------\n ax : matplotlib.axes.Axes\n The Axes to plot into.\n xlabels : list of str\n The category names to be displayed on the x-axis.\n values : (M, N) array-like\n The data values.\n Rows are the groups (len(group_labels) == M).\n Columns are the categories (len(xlabels) == N).\n group_labels : list of str\n The group labels displayed in the legend.\n \"\"\"\n\n def label_bars(heights, rects):\n \"\"\"Attach a text label on top of each bar.\"\"\"\n for height, rect in zip(heights, rects):\n ax.annotate(f'{height}',\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 4), # 4 points vertical offset.\n textcoords='offset points',\n ha='center', va='bottom')\n\n values = np.asarray(values)\n x = np.arange(values.shape[1])\n ax.set_xticks(x, labels=xlabels)\n spacing = 0.3 # spacing between hat groups\n width = (1 - spacing) / values.shape[0]\n heights0 = values[0]\n for i, (heights, group_label) in enumerate(zip(values, group_labels)):\n style = {'fill': False} if i == 0 else {'edgecolor': 'black'}\n rects = ax.bar(x - spacing/2 + i * width, heights - heights0,\n width, bottom=heights0, label=group_label, **style)\n label_bars(heights, rects)\n\n\n# initialise labels and a numpy array make sure you have\n# N labels of N number of values in the array\nxlabels = ['I', 'II', 'III', 'IV', 'V']\nplayerA = np.array([5, 15, 22, 20, 25])\nplayerB = np.array([25, 32, 34, 30, 27])\n\nfig, ax = plt.subplots()\nhat_graph(ax, xlabels, [playerA, playerB], ['Player A', 'Player B'])\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_xlabel('Games')\nax.set_ylabel('Score')\nax.set_ylim(0, 60)\nax.set_title('Scores by number of game and players')\nax.legend()\n\nfig.tight_layout()\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.bar` / `matplotlib.pyplot.bar`\n - `matplotlib.axes.Axes.annotate` / `matplotlib.pyplot.annotate`\n\n.. tags::\n\n component: annotate\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.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}