{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Center labels between ticks\n\nTick labels are aligned relative to their associated tick, and are by default\ncentered.\n\nHowever, there is no direct way to center the labels between ticks. To fake\nthis behavior, one can place a minor tick in between the major ticks. Then\nlabel the minor tick, and hide the minor tick lines and the major tick labels.\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\n# The NullFormatter removes the major tick labels\nax.xaxis.set_major_formatter(ticker.NullFormatter())\nax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))\n\n# Remove the minor tick lines\nax.tick_params(axis='x', which='minor', tick1On=False, tick2On=False)\n\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.12.15" } }, "nbformat": 4, "nbformat_minor": 0 }