{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Fitting a Polynomial\n\nThis example demonstrates computing a polynomial fit to 1D data from an Iris\ncube, adding the fit to the cube's metadata, and plotting both the 1D data and\nthe fit.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport iris\nimport iris.quickplot as qplt\n\n\ndef main():\n    # Load some test data.\n    fname = iris.sample_data_path(\"A1B_north_america.nc\")\n    cube = iris.load_cube(fname)\n\n    # Extract a single time series at a latitude and longitude point.\n    location = next(cube.slices([\"time\"]))\n\n    # Calculate a polynomial fit to the data at this time series.\n    x_points = location.coord(\"time\").points\n    y_points = location.data\n    degree = 2\n\n    p = np.polyfit(x_points, y_points, degree)\n    y_fitted = np.polyval(p, x_points)\n\n    # Add the polynomial fit values to the time series to take\n    # full advantage of Iris plotting functionality.\n    long_name = \"degree_{}_polynomial_fit_of_{}\".format(degree, cube.name())\n    fit = iris.coords.AuxCoord(\n        y_fitted, long_name=long_name, units=location.units\n    )\n    location.add_aux_coord(fit, 0)\n\n    qplt.plot(location.coord(\"time\"), location, label=\"data\")\n    qplt.plot(\n        location.coord(\"time\"),\n        location.coord(long_name),\n        \"g-\",\n        label=\"polynomial fit\",\n    )\n    plt.legend(loc=\"best\")\n    plt.title(\"Trend of US air temperature over time\")\n\n    qplt.show()\n\n\nif __name__ == \"__main__\":\n    main()"
      ]
    }
  ],
  "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.10.8"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}