{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "TCXpDyvdn_XX"
   },
   "source": [
    "# Multi-View Composition\n",
    "\n",
    "When visualizing a number of different data fields, we might be tempted to use as many visual encoding channels as we can: `x`, `y`, `color`, `size`, `shape`, and so on. However, as the number of encoding channels increases, a chart can rapidly become cluttered and difficult to read. An alternative to \"over-loading\" a single chart is to instead _compose multiple charts_ in a way that facilitates rapid comparisons.\n",
    "\n",
    "In this notebook, we will examine a variety of operations for _multi-view composition_:\n",
    "\n",
    "- _layer_: place compatible charts directly on top of each other,\n",
    "- _facet_: partition data into multiple charts, organized in rows or columns,\n",
    "- _concatenate_: position arbitrary charts within a shared layout, and\n",
    "- _repeat_: take a base chart specification and apply it to multiple data fields.\n",
    "\n",
    "We'll then look at how these operations form a _view composition algebra_, in which the operations can be combined to build a variety of complex multi-view displays.\n",
    "\n",
    "_This notebook is part of the [data visualization curriculum](https://github.com/uwdata/visualization-curriculum)._"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "dIig-LFMn1DY"
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import altair as alt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "gaYNlguioJYK"
   },
   "source": [
    "## Weather Data\n",
    "\n",
    "We will be visualizing weather statistics for the U.S. cities of Seattle and New York. Let's load the dataset and peek at the first and last 10 rows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "r3obq-Ksn8W5"
   },
   "outputs": [],
   "source": [
    "weather = 'https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 359
    },
    "colab_type": "code",
    "id": "NFKYk5waoSVd",
    "outputId": "49003cdc-647a-4a87-8c9b-293b3f7e153f"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>location</th>\n",
       "      <th>date</th>\n",
       "      <th>precipitation</th>\n",
       "      <th>temp_max</th>\n",
       "      <th>temp_min</th>\n",
       "      <th>wind</th>\n",
       "      <th>weather</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Seattle</td>\n",
       "      <td>2012-01-01</td>\n",
       "      <td>0.0</td>\n",
       "      <td>12.8</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.7</td>\n",
       "      <td>drizzle</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Seattle</td>\n",
       "      <td>2012-01-02</td>\n",
       "      <td>10.9</td>\n",
       "      <td>10.6</td>\n",
       "      <td>2.8</td>\n",
       "      <td>4.5</td>\n",
       "      <td>rain</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Seattle</td>\n",
       "      <td>2012-01-03</td>\n",
       "      <td>0.8</td>\n",
       "      <td>11.7</td>\n",
       "      <td>7.2</td>\n",
       "      <td>2.3</td>\n",
       "      <td>rain</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Seattle</td>\n",
       "      <td>2012-01-04</td>\n",
       "      <td>20.3</td>\n",
       "      <td>12.2</td>\n",
       "      <td>5.6</td>\n",
       "      <td>4.7</td>\n",
       "      <td>rain</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Seattle</td>\n",
       "      <td>2012-01-05</td>\n",
       "      <td>1.3</td>\n",
       "      <td>8.9</td>\n",
       "      <td>2.8</td>\n",
       "      <td>6.1</td>\n",
       "      <td>rain</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>Seattle</td>\n",
       "      <td>2012-01-06</td>\n",
       "      <td>2.5</td>\n",
       "      <td>4.4</td>\n",
       "      <td>2.2</td>\n",
       "      <td>2.2</td>\n",
       "      <td>rain</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>Seattle</td>\n",
       "      <td>2012-01-07</td>\n",
       "      <td>0.0</td>\n",
       "      <td>7.2</td>\n",
       "      <td>2.8</td>\n",
       "      <td>2.3</td>\n",
       "      <td>rain</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>Seattle</td>\n",
       "      <td>2012-01-08</td>\n",
       "      <td>0.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>2.8</td>\n",
       "      <td>2.0</td>\n",
       "      <td>sun</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>Seattle</td>\n",
       "      <td>2012-01-09</td>\n",
       "      <td>4.3</td>\n",
       "      <td>9.4</td>\n",
       "      <td>5.0</td>\n",
       "      <td>3.4</td>\n",
       "      <td>rain</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>Seattle</td>\n",
       "      <td>2012-01-10</td>\n",
       "      <td>1.0</td>\n",
       "      <td>6.1</td>\n",
       "      <td>0.6</td>\n",
       "      <td>3.4</td>\n",
       "      <td>rain</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  location        date  precipitation  temp_max  temp_min  wind  weather\n",
       "0  Seattle  2012-01-01            0.0      12.8       5.0   4.7  drizzle\n",
       "1  Seattle  2012-01-02           10.9      10.6       2.8   4.5     rain\n",
       "2  Seattle  2012-01-03            0.8      11.7       7.2   2.3     rain\n",
       "3  Seattle  2012-01-04           20.3      12.2       5.6   4.7     rain\n",
       "4  Seattle  2012-01-05            1.3       8.9       2.8   6.1     rain\n",
       "5  Seattle  2012-01-06            2.5       4.4       2.2   2.2     rain\n",
       "6  Seattle  2012-01-07            0.0       7.2       2.8   2.3     rain\n",
       "7  Seattle  2012-01-08            0.0      10.0       2.8   2.0      sun\n",
       "8  Seattle  2012-01-09            4.3       9.4       5.0   3.4     rain\n",
       "9  Seattle  2012-01-10            1.0       6.1       0.6   3.4     rain"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = pd.read_csv(weather)\n",
    "df.head(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 359
    },
    "colab_type": "code",
    "id": "myLKf7LWS2T4",
    "outputId": "d72e8414-f30b-47e8-8ac4-dde69462dbf4"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>location</th>\n",
       "      <th>date</th>\n",
       "      <th>precipitation</th>\n",
       "      <th>temp_max</th>\n",
       "      <th>temp_min</th>\n",
       "      <th>wind</th>\n",
       "      <th>weather</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2912</th>\n",
       "      <td>New York</td>\n",
       "      <td>2015-12-22</td>\n",
       "      <td>4.8</td>\n",
       "      <td>15.6</td>\n",
       "      <td>11.1</td>\n",
       "      <td>3.8</td>\n",
       "      <td>fog</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2913</th>\n",
       "      <td>New York</td>\n",
       "      <td>2015-12-23</td>\n",
       "      <td>29.5</td>\n",
       "      <td>17.2</td>\n",
       "      <td>8.9</td>\n",
       "      <td>4.5</td>\n",
       "      <td>fog</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2914</th>\n",
       "      <td>New York</td>\n",
       "      <td>2015-12-24</td>\n",
       "      <td>0.5</td>\n",
       "      <td>20.6</td>\n",
       "      <td>13.9</td>\n",
       "      <td>4.9</td>\n",
       "      <td>fog</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2915</th>\n",
       "      <td>New York</td>\n",
       "      <td>2015-12-25</td>\n",
       "      <td>2.5</td>\n",
       "      <td>17.8</td>\n",
       "      <td>11.1</td>\n",
       "      <td>0.9</td>\n",
       "      <td>fog</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2916</th>\n",
       "      <td>New York</td>\n",
       "      <td>2015-12-26</td>\n",
       "      <td>0.3</td>\n",
       "      <td>15.6</td>\n",
       "      <td>9.4</td>\n",
       "      <td>4.8</td>\n",
       "      <td>drizzle</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2917</th>\n",
       "      <td>New York</td>\n",
       "      <td>2015-12-27</td>\n",
       "      <td>2.0</td>\n",
       "      <td>17.2</td>\n",
       "      <td>8.9</td>\n",
       "      <td>5.5</td>\n",
       "      <td>fog</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2918</th>\n",
       "      <td>New York</td>\n",
       "      <td>2015-12-28</td>\n",
       "      <td>1.3</td>\n",
       "      <td>8.9</td>\n",
       "      <td>1.7</td>\n",
       "      <td>6.3</td>\n",
       "      <td>snow</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2919</th>\n",
       "      <td>New York</td>\n",
       "      <td>2015-12-29</td>\n",
       "      <td>16.8</td>\n",
       "      <td>9.4</td>\n",
       "      <td>1.1</td>\n",
       "      <td>5.3</td>\n",
       "      <td>fog</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2920</th>\n",
       "      <td>New York</td>\n",
       "      <td>2015-12-30</td>\n",
       "      <td>9.4</td>\n",
       "      <td>10.6</td>\n",
       "      <td>5.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>fog</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2921</th>\n",
       "      <td>New York</td>\n",
       "      <td>2015-12-31</td>\n",
       "      <td>1.5</td>\n",
       "      <td>11.1</td>\n",
       "      <td>6.1</td>\n",
       "      <td>5.5</td>\n",
       "      <td>fog</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      location        date  precipitation  temp_max  temp_min  wind  weather\n",
       "2912  New York  2015-12-22            4.8      15.6      11.1   3.8      fog\n",
       "2913  New York  2015-12-23           29.5      17.2       8.9   4.5      fog\n",
       "2914  New York  2015-12-24            0.5      20.6      13.9   4.9      fog\n",
       "2915  New York  2015-12-25            2.5      17.8      11.1   0.9      fog\n",
       "2916  New York  2015-12-26            0.3      15.6       9.4   4.8  drizzle\n",
       "2917  New York  2015-12-27            2.0      17.2       8.9   5.5      fog\n",
       "2918  New York  2015-12-28            1.3       8.9       1.7   6.3     snow\n",
       "2919  New York  2015-12-29           16.8       9.4       1.1   5.3      fog\n",
       "2920  New York  2015-12-30            9.4      10.6       5.0   3.0      fog\n",
       "2921  New York  2015-12-31            1.5      11.1       6.1   5.5      fog"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.tail(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "TKyMsDCoPxiC"
   },
   "source": [
    "We will create multi-view displays to examine weather within and across the cities."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "KicCeq0Gpm_j"
   },
   "source": [
    "## Layer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One of the most common ways of combining multiple charts is to *layer* marks on top of each other. If the underlying scale domains are compatible, we can merge them to form _shared axes_. If either of the `x` or `y` encodings is not compatible, we might instead create a _dual-axis chart_, which overlays marks using separate scales and axes."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Jc4hle6Npoij"
   },
   "source": [
    "### Shared Axes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "nChT_olsQ8vX"
   },
   "source": [
    "Let's start by plotting the minimum and maximum average temperatures per month:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 331
    },
    "colab_type": "code",
    "id": "iwgqOsfoyVe_",
    "outputId": "77cb9541-dc66-45ac-f06f-7d05ed093534"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-9214e350f9d64f0aad6890867f5f7116\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-9214e350f9d64f0aad6890867f5f7116\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-9214e350f9d64f0aad6890867f5f7116\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"mark\": \"area\", \"encoding\": {\"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\"}, \"y2\": {\"aggregate\": \"average\", \"field\": \"temp_min\"}}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.Chart(...)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alt.Chart(weather).mark_area().encode(\n",
    "  alt.X('month(date):T'),\n",
    "  alt.Y('average(temp_max):Q'),\n",
    "  alt.Y2('average(temp_min):Q')\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Bl1XIaeqSrzl"
   },
   "source": [
    "_The plot shows us temperature ranges for each month over the entirety of our data. However, this is pretty misleading as it aggregates the measurements for both Seattle and New York!_\n",
    "\n",
    "Let's subdivide the data by location using a color encoding, while also adjusting the mark opacity to accommodate overlapping areas:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 331
    },
    "colab_type": "code",
    "id": "PbNkncWsRKrV",
    "outputId": "fb6da544-e1e7-477e-fedc-e1f0a3dc61b4"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-df7be3deb4f84194bf2e3d04ad0b02d8\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-df7be3deb4f84194bf2e3d04ad0b02d8\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-df7be3deb4f84194bf2e3d04ad0b02d8\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"mark\": {\"type\": \"area\", \"opacity\": 0.3}, \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\"}, \"y2\": {\"aggregate\": \"average\", \"field\": \"temp_min\"}}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.Chart(...)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alt.Chart(weather).mark_area(opacity=0.3).encode(\n",
    "  alt.X('month(date):T'),\n",
    "  alt.Y('average(temp_max):Q'),\n",
    "  alt.Y2('average(temp_min):Q'),\n",
    "  alt.Color('location:N')\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "j30cu2YmTW8g"
   },
   "source": [
    "_We can see that Seattle is more temperate: warmer in the winter, and cooler in the summer._\n",
    "\n",
    "In this case we've created a layered chart without any special features by simply subdividing the area marks by color. While the chart above shows us the temperature ranges, we might also want to emphasize the middle of the range.\n",
    "\n",
    "Let's create a line chart showing the average temperature midpoint. We'll use a `calculate` transform to compute the midpoints between the minimum and maximum daily temperatures:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 331
    },
    "colab_type": "code",
    "id": "zHfuCUbyzW7q",
    "outputId": "257e2570-49f0-4502-aebb-b8b28aae3897"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-e96ed3e048c341ceb5ccd447260766f6\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-e96ed3e048c341ceb5ccd447260766f6\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-e96ed3e048c341ceb5ccd447260766f6\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"mark\": \"line\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_mid\"}}, \"transform\": [{\"calculate\": \"(+datum.temp_min + +datum.temp_max) / 2\", \"as\": \"temp_mid\"}], \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.Chart(...)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alt.Chart(weather).mark_line().transform_calculate(\n",
    "  temp_mid='(+datum.temp_min + +datum.temp_max) / 2'\n",
    ").encode(\n",
    "  alt.X('month(date):T'),\n",
    "  alt.Y('average(temp_mid):Q'),\n",
    "  alt.Color('location:N')\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "fQ8IMV3IUfYg"
   },
   "source": [
    "_Aside_: note the use of `+datum.temp_min` within the calculate transform. As we are loading the data directly from a CSV file without any special parsing instructions, the temperature values may be internally represented as string values. Adding the  `+` in front of the value forces it to be treated as a number.\n",
    "\n",
    "We'd now like to combine these charts by layering the midpoint lines over the range areas. Using the syntax `chart1 + chart2`, we can specify that we want a new layered chart in which `chart1` is the first layer and `chart2` is a second layer drawn on top:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 331
    },
    "colab_type": "code",
    "id": "DLOAw_LBzcuW",
    "outputId": "dc6a8c55-45cf-4029-fa68-29ea0214589e"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-57b764f780044e71bab8dc82bfb4029d\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-57b764f780044e71bab8dc82bfb4029d\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-57b764f780044e71bab8dc82bfb4029d\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"layer\": [{\"mark\": {\"type\": \"area\", \"opacity\": 0.3}, \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\"}, \"y2\": {\"aggregate\": \"average\", \"field\": \"temp_min\"}}}, {\"mark\": \"line\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_mid\"}}, \"transform\": [{\"calculate\": \"(+datum.temp_min + +datum.temp_max) / 2\", \"as\": \"temp_mid\"}]}], \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.LayerChart(...)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tempMinMax = alt.Chart(weather).mark_area(opacity=0.3).encode(\n",
    "  alt.X('month(date):T'),\n",
    "  alt.Y('average(temp_max):Q'),\n",
    "  alt.Y2('average(temp_min):Q'),\n",
    "  alt.Color('location:N')\n",
    ")\n",
    "\n",
    "tempMid = alt.Chart(weather).mark_line().transform_calculate(\n",
    "  temp_mid='(+datum.temp_min + +datum.temp_max) / 2'\n",
    ").encode(\n",
    "  alt.X('month(date):T'),\n",
    "  alt.Y('average(temp_mid):Q'),\n",
    "  alt.Color('location:N')\n",
    ")\n",
    "\n",
    "tempMinMax + tempMid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "CrA84n7W2mUi"
   },
   "source": [
    "_Now we have a multi-layer plot! However, the y-axis title (though informative) has become a bit long and unruly..._\n",
    "\n",
    "Let's customize our axes to clean up the plot. If we set a custom axis title within one of the layers, it will automatically be used as a shared axis title for all the layers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 331
    },
    "colab_type": "code",
    "id": "LUyPrsgf2N-R",
    "outputId": "b261942a-7c09-4aab-c296-c0516e6343b6"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-f14b6b763f5b4961b915883a22ac6283\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-f14b6b763f5b4961b915883a22ac6283\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-f14b6b763f5b4961b915883a22ac6283\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"layer\": [{\"mark\": {\"type\": \"area\", \"opacity\": 0.3}, \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"axis\": {\"format\": \"%b\"}, \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\", \"title\": \"Avg. Temperature \\u00b0C\"}, \"y2\": {\"aggregate\": \"average\", \"field\": \"temp_min\"}}}, {\"mark\": \"line\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_mid\"}}, \"transform\": [{\"calculate\": \"(+datum.temp_min + +datum.temp_max) / 2\", \"as\": \"temp_mid\"}]}], \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.LayerChart(...)"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tempMinMax = alt.Chart(weather).mark_area(opacity=0.3).encode(\n",
    "  alt.X('month(date):T', title=None, axis=alt.Axis(format='%b')),\n",
    "  alt.Y('average(temp_max):Q', title='Avg. Temperature °C'),\n",
    "  alt.Y2('average(temp_min):Q'),\n",
    "  alt.Color('location:N')\n",
    ")\n",
    "\n",
    "tempMid = alt.Chart(weather).mark_line().transform_calculate(\n",
    "  temp_mid='(+datum.temp_min + +datum.temp_max) / 2'\n",
    ").encode(\n",
    "  alt.X('month(date):T'),\n",
    "  alt.Y('average(temp_mid):Q'),\n",
    "  alt.Color('location:N')\n",
    ")\n",
    "\n",
    "tempMinMax + tempMid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "jb405Vkd3dFh"
   },
   "source": [
    "_What happens if both layers have custom axis titles? Modify the code above to find out..._\n",
    "\n",
    "Above used the `+` operator, a convenient shorthand for Altair's `layer` method. We can generate an identical layered chart using the `layer` method directly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 331
    },
    "colab_type": "code",
    "id": "aPnJVekc5iOE",
    "outputId": "07beb43c-9dd8-4cbc-9bb0-4fda3216ace8"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-564effe542344a99b84fc5300060a7e0\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-564effe542344a99b84fc5300060a7e0\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-564effe542344a99b84fc5300060a7e0\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"layer\": [{\"mark\": {\"type\": \"area\", \"opacity\": 0.3}, \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"axis\": {\"format\": \"%b\"}, \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\", \"title\": \"Avg. Temperature \\u00b0C\"}, \"y2\": {\"aggregate\": \"average\", \"field\": \"temp_min\"}}}, {\"mark\": \"line\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_mid\"}}, \"transform\": [{\"calculate\": \"(+datum.temp_min + +datum.temp_max) / 2\", \"as\": \"temp_mid\"}]}], \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.LayerChart(...)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alt.layer(tempMinMax, tempMid)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "_QwjqCdm6crv"
   },
   "source": [
    "Note that the order of inputs to a layer matters, as subsequent layers will be drawn on top of earlier layers. _Try swapping the order of the charts in the cells above. What happens? (Hint: look closely at the color of the `line` marks.)_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "WzJf0GAe1pug"
   },
   "source": [
    "### Dual-Axis Charts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "C5hcdEdPZddR"
   },
   "source": [
    "_Seattle has a reputation as a rainy city. Is that deserved?_\n",
    "\n",
    "Let's look at precipitation alongside temperature to learn more. First let's create a base plot the shows average monthly precipitation in Seattle:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 331
    },
    "colab_type": "code",
    "id": "kD70HRtQaN-e",
    "outputId": "f98c00a3-a8a6-485f-d61d-7ea40bcb6f97"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-08fe0ffc2866471fab15f5b305fb7ab3\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-08fe0ffc2866471fab15f5b305fb7ab3\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-08fe0ffc2866471fab15f5b305fb7ab3\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"mark\": {\"type\": \"line\", \"interpolate\": \"monotone\", \"stroke\": \"grey\"}, \"encoding\": {\"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"precipitation\", \"title\": \"Precipitation\"}}, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}], \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.Chart(...)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alt.Chart(weather).transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ").mark_line(\n",
    "  interpolate='monotone',\n",
    "  stroke='grey'\n",
    ").encode(\n",
    "  alt.X('month(date):T', title=None),\n",
    "  alt.Y('average(precipitation):Q', title='Precipitation')\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "nlcsyvEwaZjm"
   },
   "source": [
    "To facilitate comparison with the temperature data, let's create a new layered chart. Here's what happens if we try to layer the charts as we did earlier:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 331
    },
    "colab_type": "code",
    "id": "eezzWWPR1tJ6",
    "outputId": "f22513cc-d5b7-4c7f-9e95-f73ff3dec020"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-ab41d95d354247aa9dcf26f709a1e3bc\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-ab41d95d354247aa9dcf26f709a1e3bc\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-ab41d95d354247aa9dcf26f709a1e3bc\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"layer\": [{\"mark\": {\"type\": \"area\", \"opacity\": 0.3}, \"encoding\": {\"x\": {\"type\": \"temporal\", \"axis\": {\"format\": \"%b\"}, \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\", \"title\": \"Avg. Temperature \\u00b0C\"}, \"y2\": {\"aggregate\": \"average\", \"field\": \"temp_min\"}}, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}]}, {\"mark\": {\"type\": \"line\", \"interpolate\": \"monotone\", \"stroke\": \"grey\"}, \"encoding\": {\"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"precipitation\", \"title\": \"Precipitation\"}}, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}]}], \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.LayerChart(...)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tempMinMax = alt.Chart(weather).transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ").mark_area(opacity=0.3).encode(\n",
    "  alt.X('month(date):T', title=None, axis=alt.Axis(format='%b')),\n",
    "  alt.Y('average(temp_max):Q', title='Avg. Temperature °C'),\n",
    "  alt.Y2('average(temp_min):Q')\n",
    ")\n",
    "\n",
    "precip = alt.Chart(weather).transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ").mark_line(\n",
    "  interpolate='monotone',\n",
    "  stroke='grey'\n",
    ").encode(\n",
    "  alt.X('month(date):T'),\n",
    "  alt.Y('average(precipitation):Q', title='Precipitation')\n",
    ")\n",
    "\n",
    "alt.layer(tempMinMax, precip)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "jaRBJcj8bGsY"
   },
   "source": [
    "_The precipitation values use a much smaller range of the y-axis then the temperatures!_\n",
    "\n",
    "By default, layered charts use a *shared domain*: the values for the x-axis or y-axis are combined across all the layers to determine a shared extent. This default behavior assumes that the layered values have the same units. However, this doesn't hold up for this example, as we are combining temperature values (degrees Celsius) with precipitation values (inches)!\n",
    "\n",
    "If we want to use different y-axis scales, we need to specify how we want Altair to *resolve* the data across layers. In this case, we want to resolve the y-axis `scale` domains to be `independent` rather than use a `shared` domain. The `Chart` object produced by a layer operator includes a `resolve_scale` method with which we can specify the desired resolution:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 331
    },
    "colab_type": "code",
    "id": "c2ZZBtzecCff",
    "outputId": "770e1942-479c-4ac4-bbac-94b853c39239"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-81b33c8785924b29b814c17348c746c4\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-81b33c8785924b29b814c17348c746c4\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-81b33c8785924b29b814c17348c746c4\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"layer\": [{\"mark\": {\"type\": \"area\", \"opacity\": 0.3}, \"encoding\": {\"x\": {\"type\": \"temporal\", \"axis\": {\"format\": \"%b\"}, \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\", \"title\": \"Avg. Temperature \\u00b0C\"}, \"y2\": {\"aggregate\": \"average\", \"field\": \"temp_min\"}}, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}]}, {\"mark\": {\"type\": \"line\", \"interpolate\": \"monotone\", \"stroke\": \"grey\"}, \"encoding\": {\"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"precipitation\", \"title\": \"Precipitation\"}}, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}]}], \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"resolve\": {\"scale\": {\"y\": \"independent\"}}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.LayerChart(...)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tempMinMax = alt.Chart(weather).transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ").mark_area(opacity=0.3).encode(\n",
    "  alt.X('month(date):T', title=None, axis=alt.Axis(format='%b')),\n",
    "  alt.Y('average(temp_max):Q', title='Avg. Temperature °C'),\n",
    "  alt.Y2('average(temp_min):Q')\n",
    ")\n",
    "\n",
    "precip = alt.Chart(weather).transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ").mark_line(\n",
    "  interpolate='monotone',\n",
    "  stroke='grey'\n",
    ").encode(\n",
    "  alt.X('month(date):T'),\n",
    "  alt.Y('average(precipitation):Q', title='Precipitation')\n",
    ")\n",
    "\n",
    "alt.layer(tempMinMax, precip).resolve_scale(y='independent')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "tZ7Pkv4GdG2f"
   },
   "source": [
    "_We can now see that autumn is the rainiest season in Seattle (peaking in November), complemented by dry summers._\n",
    "\n",
    "You may have noticed some redundancy in our plot specifications above: both use the same dataset and the same filter to look at Seattle only. If you want, you can streamline the code a bit by providing the data and filter transform to the top-level layered chart. The individual layers will then inherit the data if they don't have their own data definitions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 331
    },
    "colab_type": "code",
    "id": "3XY7hQQrarSk",
    "outputId": "7360b4b6-1b15-4bc8-87f4-79d40bf6152f"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-ff5711171c9b4cacacc63b2cb00ae333\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-ff5711171c9b4cacacc63b2cb00ae333\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-ff5711171c9b4cacacc63b2cb00ae333\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"layer\": [{\"mark\": {\"type\": \"area\", \"opacity\": 0.3}, \"encoding\": {\"x\": {\"type\": \"temporal\", \"axis\": {\"format\": \"%b\"}, \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\", \"title\": \"Avg. Temperature \\u00b0C\"}, \"y2\": {\"aggregate\": \"average\", \"field\": \"temp_min\"}}}, {\"mark\": {\"type\": \"line\", \"interpolate\": \"monotone\", \"stroke\": \"grey\"}, \"encoding\": {\"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"precipitation\", \"title\": \"Precipitation\"}}}], \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"resolve\": {\"scale\": {\"y\": \"independent\"}}, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}], \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.LayerChart(...)"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tempMinMax = alt.Chart().mark_area(opacity=0.3).encode(\n",
    "  alt.X('month(date):T', title=None, axis=alt.Axis(format='%b')),\n",
    "  alt.Y('average(temp_max):Q', title='Avg. Temperature °C'),\n",
    "  alt.Y2('average(temp_min):Q')\n",
    ")\n",
    "\n",
    "precip = alt.Chart().mark_line(\n",
    "  interpolate='monotone',\n",
    "  stroke='grey'\n",
    ").encode(\n",
    "  alt.X('month(date):T'),\n",
    "  alt.Y('average(precipitation):Q', title='Precipitation')\n",
    ")\n",
    "\n",
    "alt.layer(tempMinMax, precip, data=weather).transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ").resolve_scale(y='independent')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While dual-axis charts can be useful, _they are often prone to misinterpretation_, as the different units and axis scales may be incommensurate. As is feasible, you might consider transformations that map different data fields to shared units, for example showing [quantiles](https://en.wikipedia.org/wiki/Quantile) or relative percentage change."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "2IefKqajprJd"
   },
   "source": [
    "## Facet"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "eyadekmFptag"
   },
   "source": [
    "*Faceting* involves subdividing a dataset into groups and creating a separate plot for each group. In earlier notebooks, we learned how to create faceted charts using the `row` and `column` encoding channels. We'll first review those channels and then show how they are instances of the more general `facet` operator.\n",
    "\n",
    "Let's start with a basic histogram of maximum temperature values in Seattle:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 372
    },
    "colab_type": "code",
    "id": "sYjs5JvDcZ6R",
    "outputId": "c25f5b7a-ca1f-465b-fa1d-416f3a304f2b"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-7d1c37331b964b67a83c77dda6f0389a\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-7d1c37331b964b67a83c77dda6f0389a\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-7d1c37331b964b67a83c77dda6f0389a\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"mark\": \"bar\", \"encoding\": {\"x\": {\"type\": \"quantitative\", \"bin\": true, \"field\": \"temp_max\", \"title\": \"Temperature (\\u00b0C)\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"count\"}}, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}], \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.Chart(...)"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alt.Chart(weather).mark_bar().transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ").encode(\n",
    "  alt.X('temp_max:Q', bin=True, title='Temperature (°C)'),\n",
    "  alt.Y('count():Q')\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Za775__ccf4e"
   },
   "source": [
    "_How does this temperature profile change based on the weather of a given day – that is, whether there was drizzle, fog, rain, snow, or sun?_\n",
    "\n",
    "Let's use the `column` encoding channel to facet the data by weather type. We can also use `color` as a redundant encoding, using a customized color range:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 271
    },
    "colab_type": "code",
    "id": "Q88OIqK5tm35",
    "outputId": "68b98e04-57c1-4ed4-960e-5919d0f597a4"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-d27b96d057924bf9bf713321085168c8\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-d27b96d057924bf9bf713321085168c8\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-d27b96d057924bf9bf713321085168c8\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"mark\": \"bar\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"weather\", \"scale\": {\"domain\": [\"drizzle\", \"fog\", \"rain\", \"snow\", \"sun\"], \"range\": [\"#aec7e8\", \"#c7c7c7\", \"#1f77b4\", \"#9467bd\", \"#e7ba52\"]}}, \"column\": {\"type\": \"nominal\", \"field\": \"weather\"}, \"x\": {\"type\": \"quantitative\", \"bin\": true, \"field\": \"temp_max\", \"title\": \"Temperature (\\u00b0C)\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"count\"}}, \"height\": 150, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}], \"width\": 150, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.Chart(...)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "colors = alt.Scale(\n",
    "  domain=['drizzle', 'fog', 'rain', 'snow', 'sun'],\n",
    "  range=['#aec7e8', '#c7c7c7', '#1f77b4', '#9467bd', '#e7ba52']\n",
    ")\n",
    "\n",
    "alt.Chart(weather).mark_bar().transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ").encode(\n",
    "  alt.X('temp_max:Q', bin=True, title='Temperature (°C)'),\n",
    "  alt.Y('count():Q'),\n",
    "  alt.Color('weather:N', scale=colors),\n",
    "  alt.Column('weather:N')\n",
    ").properties(\n",
    "  width=150,\n",
    "  height=150\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "lNspGpzQdlI8"
   },
   "source": [
    "_Unsurprisingly, those rare snow days center on the coldest temperatures, followed by rainy and foggy days. Sunny days are warmer and, despite Seattle stereotypes, are the most plentiful. Though as any Seattleite can tell you, the drizzle occasionally comes, no matter the temperature!_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "PxQ1VwQjXJZt"
   },
   "source": [
    "In addition to `row` and `column` encoding channels *within* a chart definition, we can take a basic chart definition and apply faceting using an explicit `facet` operator.\n",
    "\n",
    "Let's recreate the chart above, but this time using `facet`. We start with the same basic histogram definition, but remove the data source, filter transform, and column channel. We can then invoke the `facet` method, passing in the data and specifying that we should facet into columns according to the `weather` field. The `facet` method accepts both `row` and `column` arguments. The two can be used together to create a 2D grid of faceted plots.\n",
    "\n",
    "Finally we include our filter transform, applying it to the top-level faceted chart. While we could apply the filter transform to the histogram definition as before, that is slightly less efficient. Rather than filter out \"New York\" values within each facet cell, applying the filter to the faceted chart lets Vega-Lite know that we can filter out those values up front, prior to the facet subdivision."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "zbH63h3VWoxB",
    "outputId": "c0a8bcd2-08ec-4496-f572-7e476e7cb643"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-b5e43c4a7439427faa7d3971913b3970\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-b5e43c4a7439427faa7d3971913b3970\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-b5e43c4a7439427faa7d3971913b3970\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"facet\": {\"column\": {\"type\": \"nominal\", \"field\": \"weather\"}}, \"spec\": {\"mark\": \"bar\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"weather\", \"scale\": {\"domain\": [\"drizzle\", \"fog\", \"rain\", \"snow\", \"sun\"], \"range\": [\"#aec7e8\", \"#c7c7c7\", \"#1f77b4\", \"#9467bd\", \"#e7ba52\"]}}, \"x\": {\"type\": \"quantitative\", \"bin\": true, \"field\": \"temp_max\", \"title\": \"Temperature (\\u00b0C)\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"count\"}}, \"height\": 150, \"width\": 150}, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}], \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.FacetChart(...)"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "colors = alt.Scale(\n",
    "  domain=['drizzle', 'fog', 'rain', 'snow', 'sun'],\n",
    "  range=['#aec7e8', '#c7c7c7', '#1f77b4', '#9467bd', '#e7ba52']\n",
    ")\n",
    "\n",
    "alt.Chart().mark_bar().encode(\n",
    "  alt.X('temp_max:Q', bin=True, title='Temperature (°C)'),\n",
    "  alt.Y('count():Q'),\n",
    "  alt.Color('weather:N', scale=colors)\n",
    ").properties(\n",
    "  width=150,\n",
    "  height=150\n",
    ").facet(\n",
    "  data=weather,\n",
    "  column='weather:N'\n",
    ").transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "p-2HTw75YmxV"
   },
   "source": [
    "Given all the extra code above, why would we want to use an explicit `facet` operator? For basic charts, we should certainly use the `column` or `row` encoding channels if we can. However, using the `facet` operator explicitly is useful if we want to facet composed views, such as layered charts.\n",
    "\n",
    "Let's revisit our layered temperature plots from earlier. Instead of plotting data for New York and Seattle in the same plot, let's break them up into separate facets. The individual chart definitions are nearly the same as before: one area chart and one line chart. The only difference is that this time we won't pass the data directly to the chart constructors; we'll wait and pass it to the facet operator later. We can layer the charts much as before, then invoke `facet` on the layered chart object, passing in the data and specifying `column` facets based on the `location` field:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 404
    },
    "colab_type": "code",
    "id": "DXPaA6CylJQE",
    "outputId": "29cd36bb-babc-4b4b-8820-75175feb7d23"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-42d1e429d1d84f01a58a0752de2dafa8\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-42d1e429d1d84f01a58a0752de2dafa8\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-42d1e429d1d84f01a58a0752de2dafa8\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"facet\": {\"column\": {\"type\": \"nominal\", \"field\": \"location\"}}, \"spec\": {\"layer\": [{\"mark\": {\"type\": \"area\", \"opacity\": 0.3}, \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"axis\": {\"format\": \"%b\"}, \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\", \"title\": \"Avg. Temperature (\\u00b0C)\"}, \"y2\": {\"aggregate\": \"average\", \"field\": \"temp_min\"}}}, {\"mark\": \"line\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_mid\"}}, \"transform\": [{\"calculate\": \"(+datum.temp_min + +datum.temp_max) / 2\", \"as\": \"temp_mid\"}]}]}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.FacetChart(...)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tempMinMax = alt.Chart().mark_area(opacity=0.3).encode(\n",
    "  alt.X('month(date):T', title=None, axis=alt.Axis(format='%b')),\n",
    "  alt.Y('average(temp_max):Q', title='Avg. Temperature (°C)'),\n",
    "  alt.Y2('average(temp_min):Q'),\n",
    "  alt.Color('location:N')\n",
    ")\n",
    "\n",
    "tempMid = alt.Chart().mark_line().transform_calculate(\n",
    "  temp_mid='(+datum.temp_min + +datum.temp_max) / 2'\n",
    ").encode(\n",
    "  alt.X('month(date):T'),\n",
    "  alt.Y('average(temp_mid):Q'),\n",
    "  alt.Color('location:N')\n",
    ")\n",
    "\n",
    "alt.layer(tempMinMax, tempMid).facet(\n",
    "  data=weather,\n",
    "  column='location:N'\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "dH3laH2hZ_Er"
   },
   "source": [
    "The faceted charts we have seen so far use the same axis scale domains across the facet cells. This default of using *shared* scales and axes helps aid accurate comparison of values. However, in some cases you may wish to scale each chart independently, for example if the range of values in the cells differs significantly.\n",
    "\n",
    "Similar to layered charts, faceted charts also support _resolving_ to independent scales or axes across plots. Let's see what happens if we call the `resolve_axis` method to request `independent` y-axes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "tdkplJytl4vh",
    "outputId": "602817e3-0824-44ef-dc5a-3e2ced485cfa"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-ee0c9eb9f0964e9ebe15166542d211d7\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-ee0c9eb9f0964e9ebe15166542d211d7\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-ee0c9eb9f0964e9ebe15166542d211d7\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"facet\": {\"column\": {\"type\": \"nominal\", \"field\": \"location\"}}, \"spec\": {\"layer\": [{\"mark\": {\"type\": \"area\", \"opacity\": 0.3}, \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"axis\": {\"format\": \"%b\"}, \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\", \"title\": \"Avg. Temperature (\\u00b0C)\"}, \"y2\": {\"aggregate\": \"average\", \"field\": \"temp_min\"}}}, {\"mark\": \"line\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_mid\"}}, \"transform\": [{\"calculate\": \"(+datum.temp_min + +datum.temp_max) / 2\", \"as\": \"temp_mid\"}]}]}, \"resolve\": {\"axis\": {\"y\": \"independent\"}}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.FacetChart(...)"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tempMinMax = alt.Chart().mark_area(opacity=0.3).encode(\n",
    "  alt.X('month(date):T', title=None, axis=alt.Axis(format='%b')),\n",
    "  alt.Y('average(temp_max):Q', title='Avg. Temperature (°C)'),\n",
    "  alt.Y2('average(temp_min):Q'),\n",
    "  alt.Color('location:N')\n",
    ")\n",
    "\n",
    "tempMid = alt.Chart().mark_line().transform_calculate(\n",
    "  temp_mid='(+datum.temp_min + +datum.temp_max) / 2'\n",
    ").encode(\n",
    "  alt.X('month(date):T'),\n",
    "  alt.Y('average(temp_mid):Q'),\n",
    "  alt.Color('location:N')\n",
    ")\n",
    "\n",
    "alt.layer(tempMinMax, tempMid).facet(\n",
    "  data=weather,\n",
    "  column='location:N'\n",
    ").resolve_axis(y='independent')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "J9UK1nYKa2hM"
   },
   "source": [
    "_The chart above looks largely unchanged, but the plot for Seattle now includes its own axis._\n",
    "\n",
    "What if we instead call `resolve_scale` to resolve the underlying scale domains?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 416
    },
    "colab_type": "code",
    "id": "VjRyVRVfbCll",
    "outputId": "3b140df2-76f9-4f6d-df74-b38cb7d6e9f5"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-3bc92a318c26438993793e665a0c3839\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-3bc92a318c26438993793e665a0c3839\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-3bc92a318c26438993793e665a0c3839\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"facet\": {\"column\": {\"type\": \"nominal\", \"field\": \"location\"}}, \"spec\": {\"layer\": [{\"mark\": {\"type\": \"area\", \"opacity\": 0.3}, \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"axis\": {\"format\": \"%b\"}, \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\", \"title\": \"Avg. Temperature (\\u00b0C)\"}, \"y2\": {\"aggregate\": \"average\", \"field\": \"temp_min\"}}}, {\"mark\": \"line\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_mid\"}}, \"transform\": [{\"calculate\": \"(+datum.temp_min + +datum.temp_max) / 2\", \"as\": \"temp_mid\"}]}]}, \"resolve\": {\"scale\": {\"y\": \"independent\"}}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.FacetChart(...)"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tempMinMax = alt.Chart().mark_area(opacity=0.3).encode(\n",
    "  alt.X('month(date):T', title=None, axis=alt.Axis(format='%b')),\n",
    "  alt.Y('average(temp_max):Q', title='Avg. Temperature (°C)'),\n",
    "  alt.Y2('average(temp_min):Q'),\n",
    "  alt.Color('location:N')\n",
    ")\n",
    "\n",
    "tempMid = alt.Chart().mark_line().transform_calculate(\n",
    "  temp_mid='(+datum.temp_min + +datum.temp_max) / 2'\n",
    ").encode(\n",
    "  alt.X('month(date):T'),\n",
    "  alt.Y('average(temp_mid):Q'),\n",
    "  alt.Color('location:N')\n",
    ")\n",
    "\n",
    "alt.layer(tempMinMax, tempMid).facet(\n",
    "  data=weather,\n",
    "  column='location:N'\n",
    ").resolve_scale(y='independent')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "m6snDsbnbFho"
   },
   "source": [
    "_Now we see facet cells with different axis scale domains. In this case, using independent scales seems like a bad idea! The domains aren't very different, and one might be fooled into thinking that New York and Seattle have similar maximum summer temperatures._\n",
    "\n",
    "To borrow a cliché: just because you *can* do something, doesn't mean you *should*..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "sDyHxrLXpubO"
   },
   "source": [
    "## Concatenate"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kq4iE1w9pxMl"
   },
   "source": [
    "Faceting creates [small multiple](https://en.wikipedia.org/wiki/Small_multiple) plots that show separate subdivisions of the data. However, we might wish to create a multi-view display with different views of the *same* dataset (not subsets) or views involving *different* datasets.\n",
    "\n",
    "Altair provides *concatenation* operators to combine arbitrary charts into a composed chart. The `hconcat` operator (shorthand `|` ) performs horizontal concatenation, while the `vconcat` operator (shorthand `&`) performs vertical concatenation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "c_w_BsgFhta8"
   },
   "source": [
    "Let's start with a basic line chart showing the average maximum temperature per month for both New York and Seattle, much like we've seen before:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 355
    },
    "colab_type": "code",
    "id": "KAkDG69Xhnr_",
    "outputId": "d97fa576-5791-4912-cf3a-934d12c685d4"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-6eb9cde58726487583feb215432f4b79\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-6eb9cde58726487583feb215432f4b79\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-6eb9cde58726487583feb215432f4b79\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"mark\": \"line\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\"}}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.Chart(...)"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alt.Chart(weather).mark_line().encode(\n",
    "  alt.X('month(date):T', title=None),\n",
    "  alt.Y('average(temp_max):Q'),\n",
    "  color='location:N'\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "6-6CLOxgh88q"
   },
   "source": [
    "_What if we want to compare not just temperature over time, but also precipitation and wind levels?_\n",
    "\n",
    "Let's create a concatenated chart consisting of three plots. We'll start by defining a \"base\" chart definition that contains all the aspects that should be shared by our three plots. We can then modify this base chart to create customized variants, with different y-axis encodings for the `temp_max`, `precipitation`, and `wind` fields. We can then concatenate them using the pipe (`|`) shorthand operator:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 357
    },
    "colab_type": "code",
    "id": "crZTVb-FpHDk",
    "outputId": "6394136a-5be8-45b4-f610-744cf4cf70cb"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-b91ffb97ed6e4497b6ea4e7a0f0ffd1d\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-b91ffb97ed6e4497b6ea4e7a0f0ffd1d\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-b91ffb97ed6e4497b6ea4e7a0f0ffd1d\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"hconcat\": [{\"mark\": \"line\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\"}}, \"height\": 180, \"width\": 240}, {\"mark\": \"line\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"precipitation\"}}, \"height\": 180, \"width\": 240}, {\"mark\": \"line\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"wind\"}}, \"height\": 180, \"width\": 240}], \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.HConcatChart(...)"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "base = alt.Chart(weather).mark_line().encode(\n",
    "  alt.X('month(date):T', title=None),\n",
    "  color='location:N'\n",
    ").properties(\n",
    "  width=240,\n",
    "  height=180\n",
    ")\n",
    "\n",
    "temp = base.encode(alt.Y('average(temp_max):Q'))\n",
    "precip = base.encode(alt.Y('average(precipitation):Q'))\n",
    "wind = base.encode(alt.Y('average(wind):Q'))\n",
    "\n",
    "temp | precip | wind"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "YyJN3OIdinC-"
   },
   "source": [
    "Alternatively, we could use the more explicit `alt.hconcat()` method in lieu of the pipe `|` operator. _Try rewriting the code above to use `hconcat` instead._\n",
    "\n",
    "Vertical concatenation works similarly to horizontal concatenation. _Using the `&` operator (or `alt.vconcat` method), modify the code to use a vertical ordering instead of a horizontal ordering._\n",
    "\n",
    "Finally, note that horizontal and vertical concatenation can be combined. _What happens if you write something like `(temp | precip) & wind`?_\n",
    "\n",
    "_Aside_: Note the importance of those parentheses... what happens if you remove them? Keep in mind that these overloaded operators are still subject to [Python's operator precendence rules](https://docs.python.org/3/reference/expressions.html#operator-precedence), and so vertical concatenation with `&` will take precedence over horizontal concatenation with `|`!\n",
    "\n",
    "As we will revisit later, concatenation operators let you combine any and all charts into a multi-view dashboard!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Dmt0ai7NpyJp"
   },
   "source": [
    "## Repeat"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "thajPm3Mp0yV"
   },
   "source": [
    "The concatenation operators above are quite general, allowing arbitrary charts to be composed. Nevertheless, the example above was still a bit verbose: we have three very similar charts, yet have to define them separately and then concatenate them.\n",
    "\n",
    "For cases where only one or two variables are changing, the `repeat` operator provides a convenient shortcut for creating multiple charts. Given a *template* specification with some free variables, the repeat operator will then create a chart for each specified assignment to those variables.\n",
    "\n",
    "Let's recreate our concatenation example above using the `repeat` operator. The only aspect that changes across charts is the choice of data field for the `y` encoding channel. To create a template specification, we can use the *repeater variable* `alt.repeat('column')` as our y-axis field. This code simply states that we want to use the variable assigned to the `column` repeater, which organizes repeated charts in a horizontal direction. (As the repeater provides the field name only, we have to specify the field data type separately as `type='quantitative'`.)\n",
    "\n",
    "We then invoke the `repeat` method, passing in data field names for each column:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 357
    },
    "colab_type": "code",
    "id": "Pp3X3Aa0oc28",
    "outputId": "3c27963c-cd25-42a5-ef61-99e22f4508e5"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-335b6c80602d4ee1bbbf464d2c5dd3dd\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-335b6c80602d4ee1bbbf464d2c5dd3dd\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-335b6c80602d4ee1bbbf464d2c5dd3dd\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"repeat\": {\"column\": [\"temp_max\", \"precipitation\", \"wind\"]}, \"spec\": {\"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"mark\": \"line\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"location\"}, \"x\": {\"type\": \"temporal\", \"field\": \"date\", \"timeUnit\": \"month\", \"title\": null}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": {\"repeat\": \"column\"}}}, \"height\": 180, \"width\": 240}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.RepeatChart(...)"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alt.Chart(weather).mark_line().encode(\n",
    "  alt.X('month(date):T',title=None),\n",
    "  alt.Y(alt.repeat('column'), aggregate='average', type='quantitative'),\n",
    "  color='location:N'\n",
    ").properties(\n",
    "  width=240,\n",
    "  height=180\n",
    ").repeat(\n",
    "  column=['temp_max', 'precipitation', 'wind']\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "WeO93wdcm-kl"
   },
   "source": [
    "Repetition is supported for both columns and rows. _What happens if you modify the code above to use `row` instead of `column`?_\n",
    "\n",
    "We can also use `row` and `column` repetition together! One common visualization for exploratory data analysis is the [scatter plot matrix (or SPLOM)](https://en.wikipedia.org/wiki/Scatter_plot#Scatterplot_matrices). Given a collection of variables to inspect, a SPLOM provides a grid of all pairwise plots of those variables, allowing us to assess potential associations.\n",
    "\n",
    "Let's use the `repeat` operator to create a SPLOM for the `temp_max`, `precipitation`, and `wind` fields. We first create our template specification, with repeater variables for both the x- and y-axis data fields. We then invoke `repeat`, passing in arrays of field names to use for both `row` and `column`. Altair will then generate the [cross product (or, Cartesian product)](https://en.wikipedia.org/wiki/Cartesian_product) to create the full space of repeated charts:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 630
    },
    "colab_type": "code",
    "id": "pEzPoVN_mtJr",
    "outputId": "e0589555-41c5-4cb4-dd78-7653ecc841b9"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-18c53aa800f849f6b7905a522ab12a9b\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-18c53aa800f849f6b7905a522ab12a9b\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-18c53aa800f849f6b7905a522ab12a9b\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"repeat\": {\"column\": [\"wind\", \"precipitation\", \"temp_max\"], \"row\": [\"temp_max\", \"precipitation\", \"wind\"]}, \"spec\": {\"mark\": {\"type\": \"point\", \"filled\": true, \"opacity\": 0.5, \"size\": 15}, \"encoding\": {\"x\": {\"type\": \"quantitative\", \"field\": {\"repeat\": \"column\"}}, \"y\": {\"type\": \"quantitative\", \"field\": {\"repeat\": \"row\"}}}, \"height\": 150, \"width\": 150}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}], \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.RepeatChart(...)"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alt.Chart().mark_point(filled=True, size=15, opacity=0.5).encode(\n",
    "  alt.X(alt.repeat('column'), type='quantitative'),\n",
    "  alt.Y(alt.repeat('row'), type='quantitative')\n",
    ").properties(\n",
    "  width=150,\n",
    "  height=150\n",
    ").repeat(\n",
    "  data=weather,\n",
    "  row=['temp_max', 'precipitation', 'wind'],\n",
    "  column=['wind', 'precipitation', 'temp_max']\n",
    ").transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "zwemGUsXp1m8"
   },
   "source": [
    "_Looking at these plots, there does not appear to be a strong association between precipitation and wind, though we do see that extreme wind and precipitation events occur in similar temperature ranges (~5-15° C). However, this observation is not particularly surprising: if we revisit our histogram at the beginning of the facet section, we can plainly see that the days with maximum temperatures in the range of 5-15° C are the most commonly occurring._\n",
    "\n",
    "*Modify the code above to get a better understanding of chart repetition. Try adding another variable (`temp_min`) to the SPLOM. What happens if you rearrange the order of the field names in either the `row` or `column` parameters for the `repeat` operator?*\n",
    "\n",
    "_Finally, to really appreciate what the `repeat` operator provides, take a moment to imagine how you might recreate the SPLOM above using only `hconcat` and `vconcat`!_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "bNGvvh6dp2Ba"
   },
   "source": [
    "## A View Composition Algebra"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "MxKKfCjX44Dn"
   },
   "source": [
    "Together, the composition operators `layer`, `facet`, `concat`, and `repeat` form a *view composition algebra*: the various operators can be combined to construct a variety of multi-view visualizations.\n",
    "\n",
    "As an example, let's start with two basic charts: a histogram and a simple line (a single `rule` mark) showing a global average."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 331
    },
    "colab_type": "code",
    "id": "JG_OLPpR5yUN",
    "outputId": "6776832d-c756-4936-e40d-954c18d3630b"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-e84aa40a975b4d399237c4479ef5a908\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-e84aa40a975b4d399237c4479ef5a908\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-e84aa40a975b4d399237c4479ef5a908\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"hconcat\": [{\"mark\": \"bar\", \"encoding\": {\"x\": {\"type\": \"ordinal\", \"field\": \"date\", \"timeUnit\": \"month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\"}}, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}]}, {\"mark\": {\"type\": \"rule\", \"stroke\": \"firebrick\"}, \"encoding\": {\"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": \"temp_max\"}}, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}]}], \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.HConcatChart(...)"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "basic1 = alt.Chart(weather).transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ").mark_bar().encode(\n",
    "  alt.X('month(date):O'),\n",
    "  alt.Y('average(temp_max):Q')\n",
    ")\n",
    "\n",
    "basic2 = alt.Chart(weather).transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ").mark_rule(stroke='firebrick').encode(\n",
    "  alt.Y('average(temp_max):Q')\n",
    ")\n",
    "\n",
    "basic1 | basic2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "w2LRQzyi6SVs"
   },
   "source": [
    "We can then combine the two charts using a `layer` operator, and then `repeat` that layered chart to show histograms with overlaid averages for multiple fields:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 181
    },
    "colab_type": "code",
    "id": "oi06I8yk0EUj",
    "outputId": "8f74c396-ae7d-462f-a156-427c14eda87f"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-bcb72ab9b67e47169ceabcf9fce5421a\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-bcb72ab9b67e47169ceabcf9fce5421a\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-bcb72ab9b67e47169ceabcf9fce5421a\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"repeat\": {\"column\": [\"temp_max\", \"precipitation\", \"wind\"]}, \"spec\": {\"layer\": [{\"mark\": \"bar\", \"encoding\": {\"x\": {\"type\": \"ordinal\", \"field\": \"date\", \"timeUnit\": \"month\", \"title\": \"Month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": {\"repeat\": \"column\"}}}}, {\"mark\": {\"type\": \"rule\", \"stroke\": \"firebrick\"}, \"encoding\": {\"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": {\"repeat\": \"column\"}}}}], \"height\": 150, \"width\": 200}, \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}], \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.RepeatChart(...)"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alt.layer(\n",
    "  alt.Chart().mark_bar().encode(\n",
    "    alt.X('month(date):O', title='Month'),\n",
    "    alt.Y(alt.repeat('column'), aggregate='average', type='quantitative')\n",
    "  ),\n",
    "  alt.Chart().mark_rule(stroke='firebrick').encode(\n",
    "    alt.Y(alt.repeat('column'), aggregate='average', type='quantitative')\n",
    "  )\n",
    ").properties(\n",
    "  width=200,\n",
    "  height=150\n",
    ").repeat(\n",
    "  data=weather,\n",
    "  column=['temp_max', 'precipitation', 'wind']\n",
    ").transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "cjW4vHVtp8mP"
   },
   "source": [
    "Focusing only on the multi-view composition operators, the model for the visualization above is:\n",
    "\n",
    "```\n",
    "repeat(column=[...])\n",
    "|- layer\n",
    "   |- basic1\n",
    "   |- basic2\n",
    "```\n",
    "\n",
    "Now let's explore how we can apply *all* the operators within a final [dashboard](https://en.wikipedia.org/wiki/Dashboard_%28business%29) that provides an overview of Seattle weather. We'll combine the SPLOM and faceted histogram displays from earlier sections with the repeated histograms above:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-8313f977bb5b45ec980976c0a393f614\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-8313f977bb5b45ec980976c0a393f614\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-8313f977bb5b45ec980976c0a393f614\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else if (typeof vegaEmbed === \"function\") {\n",
       "      displayChart(vegaEmbed);\n",
       "    } else {\n",
       "      loadScript(\"vega\")\n",
       "        .then(() => loadScript(\"vega-lite\"))\n",
       "        .then(() => loadScript(\"vega-embed\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}, \"axis\": {\"labelAngle\": 0}}, \"vconcat\": [{\"hconcat\": [{\"repeat\": {\"column\": [\"wind\", \"precipitation\", \"temp_max\"], \"row\": [\"temp_max\", \"precipitation\", \"wind\"]}, \"spec\": {\"mark\": {\"type\": \"point\", \"filled\": true, \"opacity\": 0.5, \"size\": 15}, \"encoding\": {\"x\": {\"type\": \"quantitative\", \"field\": {\"repeat\": \"column\"}}, \"y\": {\"type\": \"quantitative\", \"field\": {\"repeat\": \"row\"}}}, \"height\": 125, \"width\": 125}}, {\"repeat\": {\"row\": [\"temp_max\", \"precipitation\", \"wind\"]}, \"spec\": {\"layer\": [{\"mark\": \"bar\", \"encoding\": {\"x\": {\"type\": \"ordinal\", \"field\": \"date\", \"timeUnit\": \"month\", \"title\": \"Month\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": {\"repeat\": \"row\"}}}}, {\"mark\": {\"type\": \"rule\", \"stroke\": \"firebrick\"}, \"encoding\": {\"y\": {\"type\": \"quantitative\", \"aggregate\": \"average\", \"field\": {\"repeat\": \"row\"}}}}], \"height\": 125, \"width\": 175}}]}, {\"facet\": {\"column\": {\"type\": \"nominal\", \"field\": \"weather\"}}, \"spec\": {\"mark\": \"bar\", \"encoding\": {\"color\": {\"type\": \"nominal\", \"field\": \"weather\", \"scale\": {\"domain\": [\"drizzle\", \"fog\", \"rain\", \"snow\", \"sun\"], \"range\": [\"#aec7e8\", \"#c7c7c7\", \"#1f77b4\", \"#9467bd\", \"#e7ba52\"]}}, \"x\": {\"type\": \"quantitative\", \"bin\": true, \"field\": \"temp_max\", \"title\": \"Temperature (\\u00b0C)\"}, \"y\": {\"type\": \"quantitative\", \"aggregate\": \"count\"}}, \"height\": 100, \"width\": 115}}], \"data\": {\"url\": \"https://cdn.jsdelivr.net/npm/vega-datasets@1/data/weather.csv\"}, \"resolve\": {\"legend\": {\"color\": \"independent\"}}, \"title\": \"Seattle Weather Dashboard\", \"transform\": [{\"filter\": \"datum.location == \\\"Seattle\\\"\"}], \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.8.1.json\"}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.VConcatChart(...)"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "splom = alt.Chart().mark_point(filled=True, size=15, opacity=0.5).encode(\n",
    "  alt.X(alt.repeat('column'), type='quantitative'),\n",
    "  alt.Y(alt.repeat('row'), type='quantitative')\n",
    ").properties(\n",
    "  width=125,\n",
    "  height=125\n",
    ").repeat(\n",
    "  row=['temp_max', 'precipitation', 'wind'],\n",
    "  column=['wind', 'precipitation', 'temp_max']\n",
    ")\n",
    "\n",
    "dateHist = alt.layer(\n",
    "  alt.Chart().mark_bar().encode(\n",
    "    alt.X('month(date):O', title='Month'),\n",
    "    alt.Y(alt.repeat('row'), aggregate='average', type='quantitative')\n",
    "  ),\n",
    "  alt.Chart().mark_rule(stroke='firebrick').encode(\n",
    "    alt.Y(alt.repeat('row'), aggregate='average', type='quantitative')\n",
    "  )\n",
    ").properties(\n",
    "  width=175,\n",
    "  height=125\n",
    ").repeat(\n",
    "  row=['temp_max', 'precipitation', 'wind']\n",
    ")\n",
    "\n",
    "tempHist = alt.Chart(weather).mark_bar().encode(\n",
    "  alt.X('temp_max:Q', bin=True, title='Temperature (°C)'),\n",
    "  alt.Y('count():Q'),\n",
    "  alt.Color('weather:N', scale=alt.Scale(\n",
    "    domain=['drizzle', 'fog', 'rain', 'snow', 'sun'],\n",
    "    range=['#aec7e8', '#c7c7c7', '#1f77b4', '#9467bd', '#e7ba52']\n",
    "  ))\n",
    ").properties(\n",
    "  width=115,\n",
    "  height=100\n",
    ").facet(\n",
    "  column='weather:N'\n",
    ")\n",
    "\n",
    "alt.vconcat(\n",
    "  alt.hconcat(splom, dateHist),\n",
    "  tempHist,\n",
    "  data=weather,\n",
    "  title='Seattle Weather Dashboard'\n",
    ").transform_filter(\n",
    "  'datum.location == \"Seattle\"'\n",
    ").resolve_legend(\n",
    "  color='independent'\n",
    ").configure_axis(\n",
    "  labelAngle=0\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "2KeY0T5G79KO"
   },
   "source": [
    "The full composition model for this dashboard is:\n",
    "\n",
    "```\n",
    "vconcat\n",
    "|- hconcat\n",
    "|  |- repeat(row=[...], column=[...])\n",
    "|  |  |- splom base chart\n",
    "|  |- repeat(row=[...])\n",
    "|     |- layer\n",
    "|        |- dateHist base chart 1\n",
    "|        |- dateHist base chart 2\n",
    "|- facet(column='weather')\n",
    "   |- tempHist base chart\n",
    "```\n",
    "\n",
    "_Phew!_ The dashboard also includes a few customizations to improve the layout:\n",
    "\n",
    "- We adjust chart `width` and `height` properties to assist alignment and ensure the full visualization fits on the screen.\n",
    "- We add `resolve_legend(color='independent')` to ensure the color legend is associated directly with the colored histograms by temperature. Otherwise, the legend will resolve to the dashboard as a whole.\n",
    "- We use `configure_axis(labelAngle=0)` to ensure that no axis labels are rotated. This helps to ensure proper alignment among the scatter plots in the SPLOM and the histograms by month on the right.\n",
    "\n",
    "_Try removing or modifying any of these adjustments and see how the dashboard layout responds!_\n",
    "\n",
    "This dashboard can be reused to show data for other locations or from other datasets. _Update the dashboard to show weather patterns for New York instead of Seattle._"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "NZzvXj7c4BpD"
   },
   "source": [
    "## Summary\n",
    "\n",
    "For more details on multi-view composition, including control over sub-plot spacing and header labels, see the [Altair Compound Charts documentation](https://altair-viz.github.io/user_guide/compound_charts.html).\n",
    "\n",
    "Now that we've seen how to compose multiple views, we're ready to put them into action. In addition to statically presenting data, multiple views can enable interactive multi-dimensional exploration. For example, using _linked selections_ we can highlight points in one view to see corresponding values highlight in other views.\n",
    "\n",
    "In the next notebook, we'll examine how to author *interactive selections* for both individual plots and multi-view compositions."
   ]
  }
 ],
 "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.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
