{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Date axis\n\nLoad a numpy record array from yahoo csv data with fields date, open, close,\nvolume, adj_close from the mpl-data/example directory. The record array\nstores the date as an np.datetime64 with a day unit ('D') in the date column.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport matplotlib.cbook as cbook\nimport matplotlib\n\nyears = mdates.YearLocator() # every year\nmonths = mdates.MonthLocator() # every month\nyearsFmt = mdates.DateFormatter(\"%Y\")\n\n\nif matplotlib.__version__ < \"3.3.0\":\n with cbook.get_sample_data(\"goog.npz\") as datafile:\n r = np.load(datafile)\nelse:\n r = cbook.get_sample_data(\"goog.npz\", np_load=True)\n\nr = r[\"price_data\"].view(np.recarray)\n\nfig, ax = plt.subplots()\nax.plot(r.date, r.adj_close)\n\n# format the ticks\nax.xaxis.set_major_locator(years)\nax.xaxis.set_major_formatter(yearsFmt)\nax.xaxis.set_minor_locator(months)\n\n# round to nearest years...\ndatemin = np.datetime64(r.date[0], \"Y\")\ndatemax = np.datetime64(r.date[-1], \"Y\") + np.timedelta64(1, \"Y\")\nax.set_xlim(datemin, datemax)\n\n\n# format the coords message box\ndef price(x):\n return \"$%1.2f\" % x\n\n\nax.format_xdata = mdates.DateFormatter(\"%Y-%m-%d\")\nax.format_ydata = price\nax.grid(True)\n\n# rotates and right aligns the x labels, and moves the bottom of the\n# axes up to make room for them\nfig.autofmt_xdate()\n\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.8.10" } }, "nbformat": 4, "nbformat_minor": 0 }