{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "776f8271-21ed-4707-a1ad-09d8c63ae95a",
   "metadata": {
    "tags": [
     "hide"
    ]
   },
   "outputs": [],
   "source": [
    "import seaborn as sns\n",
    "sns.set_theme()\n",
    "mpg = sns.load_dataset(\"mpg\")"
   ]
  },
  {
   "cell_type": "raw",
   "id": "85717971-adc9-45b0-9c4b-3f022d96179c",
   "metadata": {},
   "source": [
    "Pass `x` and `y` to see a scatter plot of the residuals after fitting a simple regression model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5aea4655-fb51-4b51-b41d-4769de50e956",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.residplot(data=mpg, x=\"weight\", y=\"displacement\")"
   ]
  },
  {
   "cell_type": "raw",
   "id": "175b6287-9240-493f-94bc-9d18258e952b",
   "metadata": {},
   "source": [
    "Structure in the residual plot can reveal a violation of linear regression assumptions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39aa84c2-d623-44be-9b0b-746f52b55fd4",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.residplot(data=mpg, x=\"horsepower\", y=\"mpg\")"
   ]
  },
  {
   "cell_type": "raw",
   "id": "bd9641e4-8df5-4751-b261-6443888fbbfe",
   "metadata": {},
   "source": [
    "Remove higher-order trends to test whether that stabilizes the residuals:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03a68199-1272-464b-8b85-7a309c22a4a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.residplot(data=mpg, x=\"horsepower\", y=\"mpg\", order=2)"
   ]
  },
  {
   "cell_type": "raw",
   "id": "b17750af-0393-4c53-8057-bf95d0de821a",
   "metadata": {},
   "source": [
    "Adding a LOWESS curve can help reveal or emphasize structure:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "494359bd-47b2-426e-9c35-14b5351eec93",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.residplot(data=mpg, x=\"horsepower\", y=\"mpg\", lowess=True, line_kws=dict(color=\"r\"))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py310",
   "language": "python",
   "name": "py310"
  },
  "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.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
