{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Standard Data Science Helpers\n",
    "import numpy as np\n",
    "import scipy\n",
    "\n",
    "import pandas as pd\n",
    "import featuretools as ft\n",
    "\n",
    "# Graphic libraries\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "plt.style.use('bmh');plt.rcParams['font.size']=18\n",
    "import seaborn as sns\n",
    "\n",
    "# Extra options \n",
    "\n",
    "pd.options.display.max_rows = 10\n",
    "pd.set_option('max_columns', 100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def ecdf_values(x):\n",
    "    \"\"\"Generate values for empirical cumulative distribution function\n",
    "    \n",
    "    Params\n",
    "    --------\n",
    "        x (array or list of numeric values): distribution for ECDF\n",
    "    \n",
    "    Returns\n",
    "    --------\n",
    "        x (array): x values\n",
    "        y (array): percentile values\n",
    "    \"\"\"\n",
    "    \n",
    "    # Sort values and find length\n",
    "    x = np.sort(x)\n",
    "    n = len(x)\n",
    "    # Create percentiles\n",
    "    y = np.arange(1, n + 1, 1) / n\n",
    "    return x, y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.09090909, 0.18181818, 0.27272727, 0.36363636, 0.45454545,\n",
       "       0.54545455, 0.63636364, 0.72727273, 0.81818182, 0.90909091,\n",
       "       1.        ])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = [32444, 12456, 14911,23064,27055,29427,47710,\n",
    "     42322,51206,75041,67713]\n",
    "\n",
    "xs, ys = ecdf_values(x)\n",
    "ys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def ecdf_plot(x, name = 'Value', plot_normal = True, log_scale=False):\n",
    "    \"\"\"ECDF plot of x\n",
    "    Params\n",
    "    --------\n",
    "        x (array or list of numerics): distribution for ECDF\n",
    "        name (str): name of the distribution, used for labeling\n",
    "        plot_normal (bool): plot the normal distribution (from mean and std of data)\n",
    "        log_scale (bool): transform the scale to logarithmic\n",
    "    \n",
    "    Returns\n",
    "    --------\n",
    "        none, displays plot\n",
    "    \n",
    "    \"\"\"\n",
    "    xs, ys = ecdf_values(x)\n",
    "    fig = plt.figure(figsize = (10, 6))\n",
    "    ax = plt.subplot(1, 1, 1)\n",
    "    plt.step(xs, ys, linewidth = 2.5, c= 'b');\n",
    "    \n",
    "    plot_range = ax.get_xlim()[1] - ax.get_xlim()[0]\n",
    "    fig_sizex = fig.get_size_inches()[0]\n",
    "    data_inch = plot_range / fig_sizex\n",
    "    right = 0.6 * data_inch + max(xs)\n",
    "    gap = right - max(xs)\n",
    "    left = min(xs) - gap\n",
    "    \n",
    "    if log_scale:\n",
    "        ax.set_xscale('log')\n",
    "        \n",
    "    if plot_normal:\n",
    "        gxs, gys = ecdf_values(np.random.normal(loc = xs.mean(), scale = xs.std(), size = 100000))\n",
    "        plt.plot(gxs, gys, 'g');\n",
    "\n",
    "    plt.vlines(x=min(xs), ymin=0, ymax=min(ys), color = 'b', linewidth = 2.5)\n",
    "    plt.xticks(size = 16); plt.yticks(size = 16)\n",
    "    plt.xlabel(f'{name}', size = 18); plt.ylabel('Percentile', size = 18);\n",
    "\n",
    "    plt.vlines(x=min(xs), ymin = min(ys), ymax=0.065, color = 'r', \n",
    "               linestyle = '-', alpha = 0.8, linewidth = 1.7)\n",
    "    plt.vlines(x=max(xs), ymin=0.935, ymax=max(ys), color = 'r', \n",
    "               linestyle = '-', alpha = 0.8, linewidth = 1.7)\n",
    "\n",
    "    plt.annotate(s = f'{min(xs):.2f}', xy = (min(xs), 0.065),\n",
    "                horizontalalignment = 'center',\n",
    "                verticalalignment = 'bottom',\n",
    "                size = 15)\n",
    "    plt.annotate(s = f'{max(xs):.2f}', xy = (max(xs), 0.935),\n",
    "                horizontalalignment = 'center',\n",
    "                verticalalignment = 'top',\n",
    "                size = 15)\n",
    "    \n",
    "    ps = [0.25, 0.5, 0.75]\n",
    "\n",
    "    for p in ps:\n",
    "\n",
    "        ax.set_xlim(left = left, right = right)\n",
    "        ax.set_ylim(bottom = 0)\n",
    "\n",
    "        value = xs[np.where(ys > p)[0][0] - 1]\n",
    "        pvalue = ys[np.where(ys > p)[0][0] - 1]\n",
    "\n",
    "        plt.hlines(y=p, xmin=left, xmax = value,\n",
    "                    linestyles = ':', colors = 'r', linewidth = 1.4);\n",
    "\n",
    "        plt.vlines(x=value, ymin=0, ymax = pvalue, \n",
    "                   linestyles = ':', colors = 'r', linewidth = 1.4)\n",
    "        \n",
    "        plt.text(x = p / 3, y = p - 0.01, \n",
    "                 transform = ax.transAxes,\n",
    "                 s = f'{int(100*p)}%', size = 15,\n",
    "                 color = 'r', alpha = 0.7)\n",
    "\n",
    "        plt.text(x = value, y = 0.01, size = 15,\n",
    "                 horizontalalignment = 'left',\n",
    "                 s = f'{value:.2f}', color = 'r', alpha = 0.8);\n",
    "\n",
    "    plt.title(f'ECDF of {name}', size = 20);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 57960 characters]\n",
      "text/plain": [
       "<Figure size 720x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ecdf_plot(np.random.randn(100), name='Normal Distribution')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 59312 characters]\n",
      "text/plain": [
       "<Figure size 720x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ecdf_plot(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.6.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
