{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2807e70",
   "metadata": {},
   "outputs": [],
   "source": [
    "import altair as alt\n",
    "import pandas as pd\n",
    "import panel as pn\n",
    "import panel_material_ui as pmui\n",
    "\n",
    "pn.extension('vega')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc2aa754",
   "metadata": {},
   "source": [
    "This example demonstrates how to leverage the brushing/linked-selections support in the Vega pane to update a table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9327af65",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_json(\"https://raw.githubusercontent.com/vega/vega/master/docs/data/penguins.json\")\n",
    "\n",
    "brush = alt.selection_interval(name='brush')  # selection of type \"interval\"\n",
    "\n",
    "chart = alt.Chart(df).mark_point().encode(\n",
    "    x=alt.X('Beak Length (mm):Q', scale=alt.Scale(zero=False)),\n",
    "    y=alt.Y('Beak Depth (mm):Q', scale=alt.Scale(zero=False)),\n",
    "    color=alt.condition(brush, 'Species:N', alt.value('lightgray'))\n",
    ").properties(\n",
    "    width=300,\n",
    "    height=300\n",
    ").add_params(\n",
    "    brush\n",
    ")\n",
    "\n",
    "vega_pane = pn.pane.Vega(chart, debounce=10)\n",
    "\n",
    "def filtered_table(selection):\n",
    "    if not selection:\n",
    "        return df.iloc[:0]\n",
    "    query = ' & '.join(\n",
    "        f'{crange[0]:.3f} <= `{col}` <= {crange[1]:.3f}'\n",
    "        for col, crange in selection.items()\n",
    "    )\n",
    "    return df.query(query)\n",
    "\n",
    "description = pn.pane.Markdown(\n",
    "    'Select points on the plot and watch the linked table update.',\n",
    "    sizing_mode='stretch_width'\n",
    ")\n",
    "\n",
    "table = pn.pane.DataFrame(\n",
    "    pn.bind(filtered_table, vega_pane.selection.param.brush),\n",
    "    height=350,\n",
    "    sizing_mode=\"stretch_width\",\n",
    ")\n",
    "\n",
    "output = pn.Row(vega_pane, table)\n",
    "\n",
    "output    "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c69e8212-3d92-439d-a950-4879bc239bf7",
   "metadata": {},
   "source": [
    "### Served App"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "883b18f6-378e-42b5-832e-fde36677632d",
   "metadata": {},
   "outputs": [],
   "source": [
    "if pn.state.served:\n",
    "    pmui.Page(\n",
    "        main=[description, output],\n",
    "        title=\"Altair Brushing\"\n",
    "    ).servable()"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
