{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Center labels between ticks\n\nTicklabels are aligned relative to their associated tick. The alignment\n'center', 'left', or 'right' can be controlled using the horizontal alignment\nproperty::\n\n for label in ax.get_xticklabels():\n label.set_horizontalalignment('right')\n\nHowever, there is no direct way to center the labels between ticks. To fake\nthis behavior, one can place a label on the minor ticks in between the major\nticks, and hide the major tick labels and minor ticks.\n\nHere is an example that labels the months, centered between the ticks.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n\nimport matplotlib.cbook as cbook\nimport matplotlib.dates as dates\nimport matplotlib.ticker as ticker\n\n# Load some financial data; Google's stock price\nr = cbook.get_sample_data('goog.npz')['price_data']\nr = r[-250:] # get the last 250 days\n\nfig, ax = plt.subplots()\nax.plot(r[\"date\"], r[\"adj_close\"])\n\nax.xaxis.set_major_locator(dates.MonthLocator())\n# 16 is a slight approximation since months differ in number of days.\nax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=16))\n\nax.xaxis.set_major_formatter(ticker.NullFormatter())\nax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))\n\n# Remove the tick lines\nax.tick_params(axis='x', which='minor', tick1On=False, tick2On=False)\n\n# Align the minor tick label\nfor label in ax.get_xticklabels(minor=True):\n label.set_horizontalalignment('center')\nimid = len(r) // 2\nax.set_xlabel(str(r[\"date\"][imid].item().year))\nplt.show()" ] } ], "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 }