{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Stock prices over 32 years\n\n.. redirect-from:: /gallery/showcase/bachelors_degrees_by_gender\n\nA graph of multiple time series that demonstrates custom styling of plot frame,\ntick lines, tick labels, and line graph properties. It also uses custom\nplacement of text labels along the right edge as an alternative to a\nconventional legend.\n\nNote: The third-party mpl style dufte_ produces similar-looking plots with less\ncode.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.cbook import get_sample_data\nimport matplotlib.transforms as mtransforms\n\nwith get_sample_data('Stocks.csv') as file:\n    stock_data = np.genfromtxt(\n        file, delimiter=',', names=True, dtype=None,\n        converters={0: lambda x: np.datetime64(x, 'D')}, skip_header=1)\n\nfig, ax = plt.subplots(1, 1, figsize=(6, 8), layout='constrained')\n\n# These are the colors that will be used in the plot\nax.set_prop_cycle(color=[\n    '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',\n    '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',\n    '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d',\n    '#17becf', '#9edae5'])\n\nstocks_name = ['IBM', 'Apple', 'Microsoft', 'Xerox', 'Amazon', 'Dell',\n               'Alphabet', 'Adobe', 'S&P 500', 'NASDAQ']\nstocks_ticker = ['IBM', 'AAPL', 'MSFT', 'XRX', 'AMZN', 'DELL', 'GOOGL',\n                 'ADBE', 'GSPC', 'IXIC']\n\n# Manually adjust the label positions vertically (units are points = 1/72 inch)\ny_offsets = dict.fromkeys(stocks_ticker, 0)\ny_offsets['IBM'] = 5\ny_offsets['AAPL'] = -5\ny_offsets['AMZN'] = -6\n\nfor nn, column in enumerate(stocks_ticker):\n    # Plot each line separately with its own color.\n    # don't include any data with NaN.\n    good = np.nonzero(np.isfinite(stock_data[column]))\n    line, = ax.plot(stock_data['Date'][good], stock_data[column][good], lw=2.5)\n\n    # Add a text label to the right end of every line. Most of the code below\n    # is adding specific offsets y position because some labels overlapped.\n    y_pos = stock_data[column][-1]\n\n    # Use an offset transform, in points, for any text that needs to be nudged\n    # up or down.\n    offset = y_offsets[column] / 72\n    trans = mtransforms.ScaledTranslation(0, offset, fig.dpi_scale_trans)\n    trans = ax.transData + trans\n\n    # Again, make sure that all labels are large enough to be easily read\n    # by the viewer.\n    ax.text(np.datetime64('2022-10-01'), y_pos, stocks_name[nn],\n            color=line.get_color(), transform=trans)\n\nax.set_xlim(np.datetime64('1989-06-01'), np.datetime64('2023-01-01'))\n\nfig.suptitle(\"Technology company stocks prices dollars (1990-2022)\",\n             ha=\"center\")\n\n# Remove the plot frame lines. They are unnecessary here.\nax.spines[:].set_visible(False)\n\n# Ensure that the axis ticks only show up on the bottom and left of the plot.\n# Ticks on the right and top of the plot are generally unnecessary.\nax.xaxis.tick_bottom()\nax.yaxis.tick_left()\nax.set_yscale('log')\n\n# Provide tick lines across the plot to help your viewers trace along\n# the axis ticks. Make sure that the lines are light and small so they\n# don't obscure the primary data lines.\nax.grid(True, 'major', 'both', ls='--', lw=.5, c='k', alpha=.3)\n\n# Remove the tick marks; they are unnecessary with the tick lines we just\n# plotted. Make sure your axis ticks are large enough to be easily read.\n# You don't want your viewers squinting to read your plot.\nax.tick_params(axis='both', which='both', labelsize='large',\n               bottom=False, top=False, labelbottom=True,\n               left=False, right=False, labelleft=True)\n\n# Finally, save the figure as a PNG.\n# You can also save it as a PDF, JPEG, etc.\n# Just change the file extension in this call.\n# fig.savefig('stock-prices.png', bbox_inches='tight')\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.pyplot.subplots`\n   - `matplotlib.axes.Axes.text`\n   - `matplotlib.axis.XAxis.tick_bottom`\n   - `matplotlib.axis.YAxis.tick_left`\n   - `matplotlib.artist.Artist.set_visible`\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.14.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}