{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "TCXpDyvdn_XX"
   },
   "source": [
    "# 複数ビューの構成\n",
    "\n",
    "複数のデータフィールドを可視化する際に、`x`、`y`、`color`、`size`、`shape`など、利用可能な視覚的エンコーディングチャネルをできるだけ多く使用したくなるかもしれません。しかし、エンコーディングチャネルの数が増えると、チャートはすぐに煩雑で読みづらくなります。一つのチャートを「過剰に負荷」する代わりに、_複数のチャートを構成_して比較を迅速に行えるようにする方法があります。\n",
    "\n",
    "このノートブックでは、_複数ビューの構成_に関するさまざまな操作を検討します:\n",
    "\n",
    "- _layer_:互換性のあるチャートを直接重ねて配置する、\n",
    "- _facet_:データを複数のチャートに分割し、行または列に整理する、\n",
    "- _concatenate_:任意のチャートを共通のレイアウト内に配置する、\n",
    "- _repeat_:基本的なチャート仕様を複数のデータフィールドに適用する。\n",
    "\n",
    "その後、これらの操作が_ビュー構成代数_を形成する方法を見ていきます。この代数を組み合わせて、さまざまな複雑な複数ビュー表示を構築することができます。\n",
    "\n",
    "_このノートブックは、[データ可視化カリキュラム](https://github.com/uwdata/visualization-curriculum) の一部です。_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "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": [
    "## 天気データ\n",
    "\n",
    "アメリカの都市、シアトルとニューヨークの天気統計を可視化します。データセットを読み込み、最初の10行と最後の10行を確認してみましょう:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "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": 3,
   "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": 4,
   "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": [
    "複数ビューの表示を作成し、各都市内および都市間の天気を調べてみましょう。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "KicCeq0Gpm_j"
   },
   "source": [
    "## レイヤー"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "複数のチャートを組み合わせる最も一般的な方法の1つは、マークを*レイヤー*として重ねることです。基盤となるスケールドメインが互換性がある場合、それらを結合して_共有軸_を形成できます。一方で、`x`または`y`のエンコーディングが互換性がない場合は、代わりに_二重軸チャート_を作成し、別々のスケールと軸を使用してマークを重ねることができます。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Jc4hle6Npoij"
   },
   "source": [
    "### 共有軸"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "nChT_olsQ8vX"
   },
   "source": [
    "まず、各月ごとの平均最低気温と平均最高気温をプロットしてみましょう:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "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-4a742d48f8654f27a6b25469ce9dbd27\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-4a742d48f8654f27a6b25469ce9dbd27\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-4a742d48f8654f27a6b25469ce9dbd27\");\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": [
    "_このプロットでは、データ全体を通じた各月の気温範囲が示されています。しかし、これはシアトルとニューヨークの測定値を集計しているため、かなり誤解を招きやすいものです!_\n",
    "\n",
    "データを場所ごとに分割するために、色のエンコーディングを使用し、重なるエリアを考慮してマークの透明度を調整してみましょう:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "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-e49cb090f98d4673bc6376c6ae80f54a\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-e49cb090f98d4673bc6376c6ae80f54a\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-e49cb090f98d4673bc6376c6ae80f54a\");\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": [
    "_シアトルはより温暖で、冬は暖かく、夏は涼しいことがわかります。_\n",
    "\n",
    "この場合、単にエリアマークを色で分割することで、特別な機能を持たないレイヤードチャートを作成しました。上記のチャートでは気温範囲が示されていますが、範囲の中央部分を強調したい場合もあります。\n",
    "\n",
    "平均気温の中央値を示すラインチャートを作成してみましょう。`calculate`変換を使用して、日々の最低気温と最高気温の中央値を計算します:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "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-35159fa4008e478d8f03dc469cb82a90\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-35159fa4008e478d8f03dc469cb82a90\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-35159fa4008e478d8f03dc469cb82a90\");\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": [
    "_補足_: `calculate`変換内で`+datum.temp_min`が使用されている点に注意してください。データを特別なパース指示なしでCSVファイルから直接読み込んでいるため、気温の値が内部的に文字列として表現されている可能性があります。値の前に`+`を付けることで、それを数値として扱うよう強制します。\n",
    "\n",
    "次に、範囲エリアの上に中央値のラインを重ねることで、これらのチャートを組み合わせたいと思います。`chart1 + chart2`という構文を使用して、新しいレイヤードチャートを作成できます。この場合、`chart1`が最初のレイヤーとなり、`chart2`がその上に描画される2番目のレイヤーになります:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "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-74c0f739ca534e4db0a7d80d4b529977\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-74c0f739ca534e4db0a7d80d4b529977\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-74c0f739ca534e4db0a7d80d4b529977\");\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": [
    "_これで複数のレイヤーを持つプロットが完成しました!しかし、y軸のタイトル(情報量が多いものの)が少し長く扱いにくくなっています…_\n",
    "\n",
    "プロットを整理するために軸をカスタマイズしてみましょう。レイヤーの1つにカスタム軸タイトルを設定すると、そのタイトルがすべてのレイヤーで共有軸タイトルとして自動的に使用されます:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "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-79835efcae274141977dbb177d12792c\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-79835efcae274141977dbb177d12792c\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-79835efcae274141977dbb177d12792c\");\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": [
    "_両方のレイヤーにカスタム軸タイトルを設定するとどうなるでしょうか?上記のコードを変更して確かめてみてください…_\n",
    "\n",
    "上記では`+`演算子を使用しましたが、これはAltairの`layer`メソッドの便利な略記法です。`layer`メソッドを直接使用して、同じレイヤードチャートを生成することもできます:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "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-b0e857ff179d4e5bbd13f71eb8877e06\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-b0e857ff179d4e5bbd13f71eb8877e06\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-b0e857ff179d4e5bbd13f71eb8877e06\");\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": [
    "レイヤーへの入力順序が重要であることに注意してください。後のレイヤーは前のレイヤーの上に描画されます。_上記のセルでチャートの順序を入れ替えてみてください。何が起こるでしょうか?(ヒント:`line`マークの色に注目してください。)_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "WzJf0GAe1pug"
   },
   "source": [
    "### 二重軸チャート"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "C5hcdEdPZddR"
   },
   "source": [
    "_シアトルは雨が多い街として有名です。それは本当なのでしょうか?_\n",
    "\n",
    "降水量と気温を並べて見てみましょう。まず、シアトルの月ごとの平均降水量を示す基本プロットを作成してみましょう:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "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-977a4951022646719179777d0406a956\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-977a4951022646719179777d0406a956\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-977a4951022646719179777d0406a956\");\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": [
    "気温データとの比較を容易にするために、新しいレイヤードチャートを作成してみましょう。以下は、先ほどと同様にチャートをレイヤー化しようとした場合の結果です:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "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-b68b83444e304018a0873d2f7c9b2581\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-b68b83444e304018a0873d2f7c9b2581\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-b68b83444e304018a0873d2f7c9b2581\");\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": [
    "_降水量の値は、気温に比べてy軸の範囲をはるかに小さく使用しています!_\n",
    "\n",
    "デフォルトでは、レイヤードチャートは*共有ドメイン*を使用します。つまり、x軸やy軸の値がすべてのレイヤーで結合され、共有範囲が決定されます。このデフォルト動作は、レイヤード値が同じ単位を持つ場合を前提としています。しかし、この例では、気温(摂氏)と降水量(インチ)を組み合わせているため、この前提は当てはまりません!\n",
    "\n",
    "異なるy軸スケールを使用したい場合、Altairにレイヤー間でデータを*どのように解決するか(resolve)*を指定する必要があります。この場合、y軸の`scale`ドメインを`shared`ではなく`independent`(独立)に設定したいと考えます。レイヤーオペレーターで作成された`Chart`オブジェクトには、`resolve_scale`メソッドがあり、希望する解決方法を指定できます:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "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-5553c8f52a294dcfb5f441f9ac9fc1ed\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-5553c8f52a294dcfb5f441f9ac9fc1ed\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-5553c8f52a294dcfb5f441f9ac9fc1ed\");\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": [
    "_これで、シアトルの最も雨の多い季節が秋(11月にピーク)であり、乾燥した夏と対照的であることがわかります。_\n",
    "\n",
    "上記のプロット仕様には、いくつかの冗長性があることに気づいたかもしれません。どちらのプロットも同じデータセットを使用し、シアトルのみを対象とする同じフィルターを適用しています。必要に応じて、コードを簡略化することができます。レイヤードチャートのトップレベルにデータとフィルター変換を提供すれば、個々のレイヤーは独自のデータ定義を持たない場合、そのデータを継承します:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "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-75875938ab7b42adbb7e4bae365eacb9\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-75875938ab7b42adbb7e4bae365eacb9\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-75875938ab7b42adbb7e4bae365eacb9\");\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": [
    "二重軸チャートは便利な場合もありますが、_誤解を招きやすい_傾向があります。これは、異なる単位や軸スケールが比較できない可能性があるためです。可能であれば、異なるデータフィールドを共通の単位にマッピングする変換を検討してください。例えば、[分位数(quantiles)](https://en.wikipedia.org/wiki/Quantile)や相対的な割合変化を示す方法があります。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "2IefKqajprJd"
   },
   "source": [
    "## ファセット"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "eyadekmFptag"
   },
   "source": [
    "*ファセット(Faceting)* は、データセットをグループに分割し、各グループごとに個別のプロットを作成する手法です。以前のノートブックでは、`row`および`column`エンコーディングチャネルを使用してファセットチャートを作成する方法を学びました。まずはそれらのチャネルを復習し、それからそれらがより一般的な`facet`演算子のインスタンスであることを示します。\n",
    "\n",
    "まず、シアトルの最高気温値の基本的なヒストグラムを作成してみましょう:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "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-4c333471c2f045fface462822ca4a650\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-4c333471c2f045fface462822ca4a650\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-4c333471c2f045fface462822ca4a650\");\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": [
    "_この気温プロファイルは、その日の天候(霧雨、霧、雨、雪、晴れなど)によってどのように変化するのでしょうか?_\n",
    "\n",
    "`column`エンコーディングチャネルを使用してデータを天候タイプでファセットしてみましょう。また、`color`を冗長エンコーディングとして使用し、カスタマイズしたカラーレンジを適用します:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "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-643de4675bc6407195958948e517dd9e\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-643de4675bc6407195958948e517dd9e\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-643de4675bc6407195958948e517dd9e\");\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": [
    "_予想通り、珍しい雪の日は最も寒い気温に集中しており、その次に雨の日や霧の日が続きます。晴れの日はより暖かく、シアトルのイメージとは異なり、最も多い日数を占めています。しかし、シアトルの住民なら誰でも知っているように、霧雨は気温に関係なく時折やってきます!_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "PxQ1VwQjXJZt"
   },
   "source": [
    "チャート定義*内*での`row`および`column`エンコーディングチャネルに加えて、基本的なチャート定義を取り、明示的な`facet`演算子を使用してファセットを適用することもできます。\n",
    "\n",
    "上記のチャートを再作成してみましょう。ただし、今回は`facet`を使用します。同じ基本的なヒストグラム定義を使用しますが、データソース、フィルター変換、列チャネルを削除します。その後、`facet`メソッドを呼び出し、データを渡して、`weather`フィールドに基づいて列にファセットするよう指定します。`facet`メソッドは`row`と`column`の両方の引数を受け入れ、これらを組み合わせてファセットされたプロットの2Dグリッドを作成することができます。\n",
    "\n",
    "最後に、フィルター変換を追加し、トップレベルのファセットチャートに適用します。以前と同様にヒストグラム定義にフィルター変換を適用することもできますが、それはわずかに効率が劣ります。各ファセットセル内で「New York」の値をフィルターアウトするのではなく、ファセットチャートにフィルターを適用することで、Vega-Liteにファセット分割の前に値をあらかじめフィルターアウトできることを知らせることができます。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "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-5b76b25a4f4b41b0819edbe02e332b0c\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-5b76b25a4f4b41b0819edbe02e332b0c\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-5b76b25a4f4b41b0819edbe02e332b0c\");\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": [
    "上記の追加コードを考慮すると、なぜ明示的な`facet`演算子を使用する必要があるのでしょうか?基本的なチャートの場合、可能であれば`column`や`row`エンコーディングチャネルを使用するべきです。しかし、`facet`演算子を明示的に使用することが便利になる場合があります。それは、レイヤードチャートのような構成されたビューをファセット化したい場合です。\n",
    "\n",
    "以前のレイヤード温度プロットを再訪してみましょう。ニューヨークとシアトルのデータを同じプロットにプロットする代わりに、別々のファセットに分けてみます。個々のチャート定義は以前とほとんど同じで、1つのエリアチャートと1つのラインチャートです。唯一の違いは、今回はデータをチャートコンストラクタに直接渡さず、後で`facet`演算子に渡すまで待つことです。チャートを以前と同様にレイヤー化し、その後レイヤードチャートオブジェクトに対して`facet`を呼び出し、データを渡して`location`フィールドに基づく`column`ファセットを指定します:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "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-2d757547ba4648a9aeb19597caeb9366\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-2d757547ba4648a9aeb19597caeb9366\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-2d757547ba4648a9aeb19597caeb9366\");\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": [
    "これまで見てきたファセットチャートでは、ファセットセル全体で同じ軸スケールドメインを使用しています。この*共有*スケールと軸を使用するデフォルト設定は、値を正確に比較するのに役立ちます。しかし、場合によっては、各チャートを独立してスケーリングしたい場合があります。例えば、セル内の値の範囲が大きく異なる場合です。\n",
    "\n",
    "レイヤードチャートと同様に、ファセットチャートもプロット間でスケールや軸を*独立*して解決(resolve)することをサポートしています。`resolve_axis`メソッドを呼び出して、`y`軸を`independent`(独立)に設定した場合に何が起こるかを見てみましょう:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "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-21ddae70557c45f2ba042b308c65c830\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-21ddae70557c45f2ba042b308c65c830\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-21ddae70557c45f2ba042b308c65c830\");\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": [
    "_上記のチャートはほとんど変わりませんが、シアトルのプロットには独自の軸が追加されました。_\n",
    "\n",
    "では、代わりに`resolve_scale`を呼び出して、基盤となるスケールドメインを解決した場合はどうなるでしょうか?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "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-413d7d9a4fc34faeb833a1cd816b3937\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-413d7d9a4fc34faeb833a1cd816b3937\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-413d7d9a4fc34faeb833a1cd816b3937\");\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": [
    "_今度は、異なる軸スケールドメインを持つファセットセルが表示されました。この場合、独立したスケールを使用するのは悪いアイデアのように見えます!ドメインはそれほど大きく異ならず、ニューヨークとシアトルが同じくらいの夏の最高気温を持つと誤解される可能性があります。_\n",
    "\n",
    "よくある格言を借りるなら、「*できる*からといって、*するべき*とは限らない」..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "sDyHxrLXpubO"
   },
   "source": [
    "## 連結"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kq4iE1w9pxMl"
   },
   "source": [
    "ファセットは、データの別々の分割を示す[*スモールマルチプル*](https://en.wikipedia.org/wiki/Small_multiple)プロットを作成します。しかし、*同じ*データセット(分割ではない)や、*異なる*データセットを含むビューで構成された表示を作成したい場合もあります。\n",
    "\n",
    "Altairは、任意のチャートを組み合わせて構成されたチャートを作成するための*連結*演算子を提供します。`hconcat`演算子(略記法として`|`)は水平連結を行い、`vconcat`演算子(略記法として`&`)は垂直連結を行います。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "c_w_BsgFhta8"
   },
   "source": [
    "まず、これまで見たことのあるような、ニューヨークとシアトルの月ごとの平均最高気温を示す基本的なラインチャートを作成してみましょう:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "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-49cd4c68fdb8411a9c7346f132fd52c3\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-49cd4c68fdb8411a9c7346f132fd52c3\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-49cd4c68fdb8411a9c7346f132fd52c3\");\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": [
    "_時間に沿った気温だけでなく、降水量や風速も比較したい場合はどうすればよいでしょうか?_\n",
    "\n",
    "3つのプロットからなる連結チャートを作成してみましょう。まず、3つのプロットで共有すべきすべての要素を含む「基本」チャート定義を作成します。その後、この基本チャートを修正して、`temp_max`、`precipitation`、`wind`フィールドのy軸エンコーディングが異なるカスタマイズされたバリエーションを作成します。それらをパイプ(`|`)略記演算子を使用して連結します:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "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-2c2f71d0fe2749e6996da8c450f4e499\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-2c2f71d0fe2749e6996da8c450f4e499\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-2c2f71d0fe2749e6996da8c450f4e499\");\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": [
    "代わりに、パイプ`|`演算子の代わりにより明示的な`alt.hconcat()`メソッドを使用することもできます。_上記のコードを`hconcat`を使用するように書き換えてみてください。_\n",
    "\n",
    "垂直連結は水平連結と同様に機能します。_`&`演算子(または`alt.vconcat`メソッド)を使用して、コードを水平配置ではなく垂直配置に変更してみてください。_\n",
    "\n",
    "最後に、水平連結と垂直連結を組み合わせることができます。_例えば、`(temp | precip) & wind`のように記述すると何が起こるか試してみてください。_\n",
    "\n",
    "_補足_:括弧の重要性に注意してください…括弧を削除すると何が起こるでしょうか?これらのオーバーロードされた演算子は依然として[Pythonの演算子優先順位ルール](https://docs.python.org/3/reference/expressions.html#operator-precedence)に従うため、垂直連結(`&`)は水平連結(`|`)よりも優先されます!\n",
    "\n",
    "後ほど詳しく説明しますが、連結演算子を使用すると、任意のチャートを組み合わせてマルチビューダッシュボードを作成できます!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Dmt0ai7NpyJp"
   },
   "source": [
    "## リピート"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "thajPm3Mp0yV"
   },
   "source": [
    "上記の連結演算子は非常に汎用的で、任意のチャートを構成することができます。しかし、上記の例はやや冗長です。同じようなチャートが3つありますが、それぞれを個別に定義し、連結する必要がありました。\n",
    "\n",
    "1つまたは2つの変数だけが変更される場合、`repeat`演算子を使用すると、複数のチャートを簡単に作成するための便利なショートカットを提供します。自由変数を含む*テンプレート*仕様を指定すると、`repeat`演算子は、その変数への指定された割り当てごとにチャートを作成します。\n",
    "\n",
    "上記の連結の例を`repeat`演算子を使用して再作成してみましょう。この例では、チャート間で変化する唯一の要素は、`y`エンコーディングチャネルに使用されるデータフィールドの選択です。テンプレート仕様を作成するには、`alt.repeat('column')`という*リピータ変数*をy軸フィールドとして使用します。このコードは、`column`リピータに割り当てられた変数を使用して、チャートを水平方向に繰り返し配置したいことを示しています(リピータはフィールド名のみを提供するため、フィールドデータ型は`type='quantitative'`として別途指定する必要があります)。\n",
    "\n",
    "その後、`repeat`メソッドを呼び出し、各列のデータフィールド名を渡します:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "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-00c05e4b72924c56aee88425cf620785\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-00c05e4b72924c56aee88425cf620785\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-00c05e4b72924c56aee88425cf620785\");\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": [
    "繰り返しは、列(`column`)だけでなく行(`row`)でもサポートされています。_上記のコードを`column`ではなく`row`を使用するように変更するとどうなるでしょうか?_\n",
    "\n",
    "また、`row`と`column`の繰り返しを組み合わせることもできます!探査的データ分析における一般的な可視化方法の1つに、[散布図行列(Scatter Plot Matrix, SPLOM)](https://en.wikipedia.org/wiki/Scatter_plot#Scatterplot_matrices)があります。調査する変数のコレクションが与えられると、SPLOMはそれらの変数のすべてのペアワイズプロットのグリッドを提供し、潜在的な関連性を評価するのに役立ちます。\n",
    "\n",
    "`repeat`演算子を使用して、`temp_max`、`precipitation`、`wind`フィールドのSPLOMを作成してみましょう。まず、x軸とy軸のデータフィールドの両方にリピータ変数を使用するテンプレート仕様を作成します。その後、`repeat`を呼び出し、`row`と`column`の両方に使用するフィールド名の配列を渡します。Altairは[直積(またはデカルト積)](https://en.wikipedia.org/wiki/Cartesian_product)を生成し、繰り返しチャートの完全な空間を作成します:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "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-67e74690bdf749d2af30124cfc9ed005\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-67e74690bdf749d2af30124cfc9ed005\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-67e74690bdf749d2af30124cfc9ed005\");\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": [
    "_これらのプロットを見ると、降水量と風速の間に強い関連性は見られませんが、極端な風や降水イベントは似たような気温範囲(約5〜15°C)で発生していることがわかります。ただし、この観察結果は特に驚くべきものではありません。ファセットセクションの冒頭で示したヒストグラムを再確認すると、5〜15°Cの最高気温の日が最も一般的に発生していることが明らかです。_\n",
    "\n",
    "*上記のコードを変更して、チャートの繰り返しについてより深く理解してみましょう。例えば、別の変数(`temp_min`)をSPLOMに追加してみてください。また、`repeat`演算子の`row`または`column`パラメータでフィールド名の順序を変更するとどうなるか試してみてください。*\n",
    "\n",
    "_最後に、`repeat`演算子が提供する利便性を本当に理解するために、`hconcat`と`vconcat`だけを使用して上記のSPLOMを再現する方法を想像してみてください!_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "bNGvvh6dp2Ba"
   },
   "source": [
    "## ビュー構成代数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "MxKKfCjX44Dn"
   },
   "source": [
    "これらの構成演算子、すなわち`layer`、`facet`、`concat`、`repeat`を組み合わせることで、*ビュー構成代数*を形成します。これらの演算子を組み合わせることで、さまざまな複数ビューの可視化を構築できます。\n",
    "\n",
    "例として、2つの基本的なチャートを作成してみましょう。1つはヒストグラム、もう1つはグローバル平均を示す単純な線(単一の`rule`マーク)です。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "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-8741893b99bb4518930513149a1d5815\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-8741893b99bb4518930513149a1d5815\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-8741893b99bb4518930513149a1d5815\");\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": [
    "次に、これらの2つのチャートを`layer`演算子を使用して組み合わせます。その後、そのレイヤードチャートを`repeat`演算子を使用して繰り返し表示し、複数のフィールドのヒストグラムに平均値を重ねたものを示します:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "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-824b6c550b0d4b54972e814c350dacff\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-824b6c550b0d4b54972e814c350dacff\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-824b6c550b0d4b54972e814c350dacff\");\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": [
    "上記の可視化のモデルは、多ビュー構成演算子に焦点を当てると以下のようになります:\n",
    "\n",
    "```\n",
    "repeat(column=[...])\n",
    "|- layer\n",
    "   |- basic1\n",
    "   |- basic2\n",
    "```\n",
    "\n",
    "これから、*すべての演算子*を適用し、シアトルの天候に関する概要を示す最終的な[ダッシュボード](https://en.wikipedia.org/wiki/Dashboard_%28business%29)を作成してみましょう。以前のセクションで作成したSPLOMとファセット化されたヒストグラム表示を、上記の繰り返しヒストグラムと組み合わせます:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-c3ac2006ad78472babd8dd02cfae61df\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-c3ac2006ad78472babd8dd02cfae61df\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-c3ac2006ad78472babd8dd02cfae61df\");\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": [
    "このダッシュボードの完全な構成モデルは以下のようになります:\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",
    "_ふぅ!_ このダッシュボードには、レイアウトを改善するためのいくつかのカスタマイズも含まれています:\n",
    "\n",
    "- チャートの`width`および`height`プロパティを調整して、レイアウトを整え、全体の可視化が画面に収まるようにしています。\n",
    "- `resolve_legend(color='independent')`を追加して、カラーレジェンドが温度ごとの色分けされたヒストグラムに直接関連付けられるようにしています。これを行わないと、レジェンドがダッシュボード全体に関連付けられてしまいます。\n",
    "- `configure_axis(labelAngle=0)`を使用して、軸ラベルが回転しないようにしています。これにより、SPLOM内の散布図や右側の月別ヒストグラムの間で適切な配置が確保されます。\n",
    "\n",
    "_これらの調整を削除または変更して、ダッシュボードのレイアウトがどのように反応するか試してみてください!_\n",
    "\n",
    "このダッシュボードは、他の場所のデータや別のデータセットを表示するために再利用できます。_ダッシュボードを更新して、シアトルではなくニューヨークの天候パターンを表示してみてください。_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "NZzvXj7c4BpD"
   },
   "source": [
    "## まとめ\n",
    "\n",
    "複数ビューの構成に関する詳細情報(サブプロット間の間隔やヘッダーラベルの制御など)については、[Altair Compound Charts ドキュメント](https://altair-viz.github.io/user_guide/compound_charts.html)を参照してください。\n",
    "\n",
    "複数のビューを構成する方法を見た今、それらを実際に活用する準備が整いました。データを静的に表示するだけでなく、複数のビューを使用することで多次元のインタラクティブな探索が可能になります。たとえば、_リンクされた選択_を使用すると、一方のビューでポイントをハイライトして、他のビューで対応する値がハイライトされる様子を確認できます。\n",
    "\n",
    "次のノートブックでは、*インタラクティブ選択*を個々のプロットや複数ビューの構成でどのように作成するかを詳しく調べます。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}