{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import panel as pn\n",
    "\n",
    "from bokeh.sampledata.autompg import autompg\n",
    "from io import StringIO\n",
    "\n",
    "pn.extension()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "years = pn.widgets.MultiChoice(\n",
    "    name='Years', options=list(autompg.yr.unique()), margin=(0, 20, 0, 0)\n",
    ")\n",
    "mpg = pn.widgets.RangeSlider(\n",
    "    name='Mile per Gallon', start=autompg.mpg.min(), end=autompg.mpg.max()\n",
    ")\n",
    "\n",
    "@pn.depends(years, mpg)\n",
    "def filtered_mpg(yrs, mpg):\n",
    "    df = autompg\n",
    "    if years.value:\n",
    "        df = autompg[autompg.yr.isin(yrs)]\n",
    "    return df[(df.mpg >= mpg[0]) & (df.mpg <= mpg[1])]\n",
    "\n",
    "@pn.depends(years, mpg)\n",
    "def filtered_file(yr, mpg):\n",
    "    df = filtered_mpg(yr, mpg)\n",
    "    sio = StringIO()\n",
    "    df.to_csv(sio)\n",
    "    sio.seek(0)\n",
    "    return sio\n",
    "\n",
    "fd = pn.widgets.FileDownload(\n",
    "    callback=filtered_file, filename='filtered_autompg.csv'\n",
    ")\n",
    "\n",
    "pn.Column(pn.Row(years, mpg), fd, pn.panel(filtered_mpg, width=600), width=600).servable()"
   ]
  }
 ],
 "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.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
