{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "# Population exercise\n",
    "\n",
    "Plot populations of hares, lynxes, and carrots\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 54624 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# 从文本文件载入数据，默认按列分割；返回二维数组 shape=(年份数, 4)\n",
    "data = np.loadtxt(\"populations.txt\")\n",
    "\n",
    "# 将各列分别赋给 year（年份）、hares（野兔）、lynxes（猞猁）、carrots（胡萝卜）\n",
    "year, hares, lynxes, carrots = data.T\n",
    "\n",
    "# 手动创建坐标轴：left=0.2, bottom=0.1, width=0.5, height=0.8（百分比，相对整个图窗）\n",
    "plt.axes((0.2, 0.1, 0.5, 0.8))\n",
    "\n",
    "# 在同一幅图里绘制三条折线：野兔、猞猁、胡萝卜随年份的变化\n",
    "plt.plot(year, hares, year, lynxes, year, carrots)\n",
    "\n",
    "# 添加图例，标签顺序与上面绘图顺序一致；loc=(1.05, 0.5) 把图例放在坐标轴右侧居中\n",
    "plt.legend((\"Hare\", \"Lynx\", \"Carrot\"), loc=(1.05, 0.5))\n",
    "\n",
    "# 显示图形\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
