import hashlib
import os
import json
import random
import collections
from operator import itemgetter
import warnings
import shutil

import jinja2

from docutils import nodes
from docutils.statemachine import ViewList
from docutils.parsers.rst import Directive
from docutils.parsers.rst.directives import flag

from sphinx.util.nodes import nested_parse_with_titles

from .utils import (
    get_docstring_and_rest,
    prev_this_next,
    create_thumbnail,
    create_generic_image,
)
from altair.utils.execeval import eval_block
from tests.examples_arguments_syntax import iter_examples_arguments_syntax
from tests.examples_methods_syntax import iter_examples_methods_syntax


EXAMPLE_MODULE = "altair.examples"


GALLERY_TEMPLATE = jinja2.Template(
    """
.. This document is auto-generated by the altair-gallery extension. Do not modify directly.

.. _{{ gallery_ref }}:

{{ title }}
{% for char in title %}-{% endfor %}

This gallery contains a selection of examples of the plots Altair can create. Some may seem fairly complicated at first glance, but they are built by combining a simple set of declarative building blocks.

Many draw upon sample datasets compiled by the `Vega <https://vega.github.io/vega/>`_ project. To access them yourself, install `vega_datasets <https://github.com/altair-viz/vega_datasets>`_.

.. code-block:: none

   python -m pip install vega_datasets

If you can't find the plots you are looking for here, make sure to check out the :ref:`altair-ecosystem` section, which has links to packages for making e.g. network diagrams and animations.

{% for grouper, group in examples %}

.. _gallery-category-{{ grouper }}:

{{ grouper }}
{% for char in grouper %}~{% endfor %}

.. raw:: html

   <span class="gallery">
   {% for example in group %}
   <a class="imagegroup" href="{{ example.name }}.html">
   <span
        class="image" alt="{{ example.title }}"
{% if example['use_svg'] %}
        style="background-image: url(..{{ image_dir }}/{{ example.name }}-thumb.svg);"
{% else %}
        style="background-image: url(..{{ image_dir }}/{{ example.name }}-thumb.png);"
{% endif %}
    ></span>

     <span class="image-title">{{ example.title }}</span>
   </a>
   {% endfor %}
   </span>

   <div style='clear:both;'></div>

{% endfor %}


.. toctree::
   :maxdepth: 2
   :caption: Examples
   :hidden:

   Gallery <self>
   Tutorials <../case_studies/exploring-weather>
"""
)

MINIGALLERY_TEMPLATE = jinja2.Template(
    """
.. raw:: html

    <div id="showcase">
      <div class="examples">
      {% for example in examples %}
      <a
        class="preview" href="{{ gallery_dir }}/{{ example.name }}.html"
{% if example['use_svg'] %}
        style="background-image: url(.{{ image_dir }}/{{ example.name }}-thumb.svg)"
{% else %}
        style="background-image: url(.{{ image_dir }}/{{ example.name }}-thumb.png)"
{% endif %}
      ></a>
      {% endfor %}
      </div>
    </div>
"""
)


EXAMPLE_TEMPLATE = jinja2.Template(
    """
:orphan:
:html_theme.sidebar_secondary.remove:

.. This document is auto-generated by the altair-gallery extension. Do not modify directly.

.. _gallery_{{ name }}:

{{ docstring }}

.. altair-plot::
    {% if code_below %}:remove-code:{% endif %}
    {% if strict %}:strict:{% endif %}

{{ code | indent(4) }}

.. tab-set::

    .. tab-item:: Method syntax
        :sync: method

        .. code:: python

{{ method_code | indent(12) }}

    .. tab-item:: Attribute syntax
        :sync: attribute

        .. code:: python

{{ code | indent(12) }}
"""
)


def save_example_pngs(examples, image_dir, make_thumbnails=True):
    """Save example pngs and (optionally) thumbnails"""
    if not os.path.exists(image_dir):
        os.makedirs(image_dir)

    # store hashes so that we know whether images need to be generated
    hash_file = os.path.join(image_dir, "_image_hashes.json")

    if os.path.exists(hash_file):
        with open(hash_file) as f:
            hashes = json.load(f)
    else:
        hashes = {}

    for example in examples:
        filename = example["name"] + (".svg" if example["use_svg"] else ".png")
        image_file = os.path.join(image_dir, filename)

        example_hash = hashlib.md5(example["code"].encode()).hexdigest()
        hashes_match = hashes.get(filename, "") == example_hash

        if hashes_match and os.path.exists(image_file):
            print("-> using cached {}".format(image_file))
        else:
            # the file changed or the image file does not exist. Generate it.
            print("-> saving {}".format(image_file))
            chart = eval_block(example["code"])
            try:
                chart.save(image_file)
                hashes[filename] = example_hash
            except ImportError:
                warnings.warn("Unable to save image: using generic image", stacklevel=1)
                create_generic_image(image_file)

            with open(hash_file, "w") as f:
                json.dump(hashes, f)

        if make_thumbnails:
            params = example.get("galleryParameters", {})
            if example["use_svg"]:
                # Thumbnail for SVG is identical to original image
                thumb_file = os.path.join(image_dir, example["name"] + "-thumb.svg")
                shutil.copyfile(image_file, thumb_file)
            else:
                thumb_file = os.path.join(image_dir, example["name"] + "-thumb.png")
                create_thumbnail(image_file, thumb_file, **params)

    # Save hashes so we know whether we need to re-generate plots
    with open(hash_file, "w") as f:
        json.dump(hashes, f)


def populate_examples(**kwds):
    """Iterate through Altair examples and extract code"""

    examples = sorted(iter_examples_arguments_syntax(), key=itemgetter("name"))
    method_examples = {x["name"]: x for x in iter_examples_methods_syntax()}

    for example in examples:
        docstring, category, code, lineno = get_docstring_and_rest(example["filename"])
        if example["name"] in method_examples.keys():
            _, _, method_code, _ = get_docstring_and_rest(
                method_examples[example["name"]]["filename"]
            )
        else:
            method_code = code
            code += (
                "# No channel encoding options are specified in this chart\n"
                "# so the code is the same as for the method-based syntax.\n"
            )
        example.update(kwds)
        if category is None:
            raise Exception(
                f"The example {example['name']} is not assigned to a category"
            )
        example.update(
            {
                "docstring": docstring,
                "title": docstring.strip().split("\n")[0],
                "code": code,
                "method_code": method_code,
                "category": category.title(),
                "lineno": lineno,
            }
        )

    return examples


class AltairMiniGalleryDirective(Directive):
    has_content = False

    option_spec = {
        "size": int,
        "names": str,
        "indices": lambda x: list(map(int, x.split())),
        "shuffle": flag,
        "seed": int,
        "titles": bool,
        "width": str,
    }

    def run(self):
        size = self.options.get("size", 15)
        names = [name.strip() for name in self.options.get("names", "").split(",")]
        indices = self.options.get("indices", [])
        shuffle = "shuffle" in self.options
        seed = self.options.get("seed", 42)
        titles = self.options.get("titles", False)
        width = self.options.get("width", None)

        env = self.state.document.settings.env
        app = env.app

        gallery_dir = app.builder.config.altair_gallery_dir

        examples = populate_examples()

        if names:
            if len(names) < size:
                raise ValueError(
                    "altair-minigallery: if names are specified, "
                    "the list must be at least as long as size."
                )
            mapping = {example["name"]: example for example in examples}
            examples = [mapping[name] for name in names]
        else:
            if indices:
                examples = [examples[i] for i in indices]
            if shuffle:
                random.seed(seed)
                random.shuffle(examples)
            if size:
                examples = examples[:size]

        include = MINIGALLERY_TEMPLATE.render(
            image_dir="/_static",
            gallery_dir=gallery_dir,
            examples=examples,
            titles=titles,
            width=width,
        )

        # parse and return documentation
        result = ViewList()
        for line in include.split("\n"):
            result.append(line, "<altair-minigallery>")
        node = nodes.paragraph()
        node.document = self.state.document
        nested_parse_with_titles(self.state, result, node)

        return node.children


def main(app):
    gallery_dir = app.builder.config.altair_gallery_dir
    target_dir = os.path.join(app.builder.srcdir, gallery_dir)
    image_dir = os.path.join(app.builder.srcdir, "_images")

    gallery_ref = app.builder.config.altair_gallery_ref
    gallery_title = app.builder.config.altair_gallery_title
    examples = populate_examples(gallery_ref=gallery_ref, code_below=True, strict=False)

    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    examples = sorted(examples, key=lambda x: x["title"])
    examples_toc = collections.OrderedDict(
        {
            "Simple Charts": [],
            "Bar Charts": [],
            "Line Charts": [],
            "Area Charts": [],
            "Circular Plots": [],
            "Scatter Plots": [],
            "Uncertainties And Trends": [],
            "Distributions": [],
            "Tables": [],
            "Maps": [],
            "Interactive Charts": [],
            "Advanced Calculations": [],
            "Case Studies": [],
        }
    )
    for d in examples:
        examples_toc[d["category"]].append(d)

    # Write the gallery index file
    with open(os.path.join(target_dir, "index.rst"), "w") as f:
        f.write(
            GALLERY_TEMPLATE.render(
                title=gallery_title,
                examples=examples_toc.items(),
                image_dir="/_static",
                gallery_ref=gallery_ref,
            )
        )

    # save the images to file
    save_example_pngs(examples, image_dir)

    # Write the individual example files
    for prev_ex, example, next_ex in prev_this_next(examples):
        if prev_ex:
            example["prev_ref"] = "gallery_{name}".format(**prev_ex)
        if next_ex:
            example["next_ref"] = "gallery_{name}".format(**next_ex)
        target_filename = os.path.join(target_dir, example["name"] + ".rst")
        with open(os.path.join(target_filename), "w", encoding="utf-8") as f:
            f.write(EXAMPLE_TEMPLATE.render(example))


def setup(app):
    app.connect("builder-inited", main)
    app.add_css_file("altair-gallery.css")
    app.add_config_value("altair_gallery_dir", "gallery", "env")
    app.add_config_value("altair_gallery_ref", "example-gallery", "env")
    app.add_config_value("altair_gallery_title", "Example Gallery", "env")
    app.add_directive_to_domain("py", "altair-minigallery", AltairMiniGalleryDirective)

sphinxext/altairgallery.py
import hashlib
import os
import json
import random
import collections
from operator import itemgetter
import warnings
import shutil

import jinja2

from docutils import nodes
from docutils.statemachine import ViewList
from docutils.parsers.rst import Directive
from docutils.parsers.rst.directives import flag

from sphinx.util.nodes import nested_parse_with_titles

from .utils import (
    get_docstring_and_rest,
    prev_this_next,
    create_thumbnail,
    create_generic_image,
)
from altair.utils.execeval import eval_block
from tests.examples_arguments_syntax import iter_examples_arguments_syntax
from tests.examples_methods_syntax import iter_examples_methods_syntax


EXAMPLE_MODULE = "altair.examples"


GALLERY_TEMPLATE = jinja2.Template(
    """
.. This document is auto-generated by the altair-gallery extension. Do not modify directly.

.. _{{ gallery_ref }}:

{{ title }}
{% for char in title %}-{% endfor %}

This gallery contains a selection of examples of the plots Altair can create. Some may seem fairly complicated at first glance, but they are built by combining a simple set of declarative building blocks.

Many draw upon sample datasets compiled by the `Vega <https://vega.github.io/vega/>`_ project. To access them yourself, install `vega_datasets <https://github.com/altair-viz/vega_datasets>`_.

.. code-block:: none

   python -m pip install vega_datasets

If you can't find the plots you are looking for here, make sure to check out the :ref:`altair-ecosystem` section, which has links to packages for making e.g. network diagrams and animations.

{% for grouper, group in examples %}

.. _gallery-category-{{ grouper }}:

{{ grouper }}
{% for char in grouper %}~{% endfor %}

.. raw:: html

   <span class="gallery">
   {% for example in group %}
   <a class="imagegroup" href="{{ example.name }}.html">
   <span
        class="image" alt="{{ example.title }}"
{% if example['use_svg'] %}
        style="background-image: url(..{{ image_dir }}/{{ example.name }}-thumb.svg);"
{% else %}
        style="background-image: url(..{{ image_dir }}/{{ example.name }}-thumb.png);"
{% endif %}
    ></span>

     <span class="image-title">{{ example.title }}</span>
   </a>
   {% endfor %}
   </span>

   <div style='clear:both;'></div>

{% endfor %}


.. toctree::
   :maxdepth: 2
   :caption: Examples
   :hidden:

   Gallery <self>
   Tutorials <../case_studies/index>
"""
)

MINIGALLERY_TEMPLATE = jinja2.Template(
    """
.. raw:: html

    <div id="showcase">
      <div class="examples">
      {% for example in examples %}
      <a
        class="preview" href="{{ gallery_dir }}/{{ example.name }}.html"
{% if example['use_svg'] %}
        style="background-image: url(.{{ image_dir }}/{{ example.name }}-thumb.svg)"
{% else %}
        style="background-image: url(.{{ image_dir }}/{{ example.name }}-thumb.png)"
{% endif %}
      ></a>
      {% endfor %}
      </div>
    </div>
"""
)


EXAMPLE_TEMPLATE = jinja2.Template(
    """
:orphan:
:html_theme.sidebar_secondary.remove:

.. This document is auto-generated by the altair-gallery extension. Do not modify directly.

.. _gallery_{{ name }}:

{{ docstring }}

.. altair-plot::
    {% if code_below %}:remove-code:{% endif %}
    {% if strict %}:strict:{% endif %}

{{ code | indent(4) }}

.. tab-set::

    .. tab-item:: Method syntax
        :sync: method

        .. code:: python

{{ method_code | indent(12) }}

    .. tab-item:: Attribute syntax
        :sync: attribute

        .. code:: python

{{ code | indent(12) }}
"""
)


def save_example_pngs(examples, image_dir, make_thumbnails=True):
    """Save example pngs and (optionally) thumbnails"""
    if not os.path.exists(image_dir):
        os.makedirs(image_dir)

    # store hashes so that we know whether images need to be generated
    hash_file = os.path.join(image_dir, "_image_hashes.json")

    if os.path.exists(hash_file):
        with open(hash_file) as f:
            hashes = json.load(f)
    else:
        hashes = {}

    for example in examples:
        filename = example["name"] + (".svg" if example["use_svg"] else ".png")
        image_file = os.path.join(image_dir, filename)

        example_hash = hashlib.md5(example["code"].encode()).hexdigest()
        hashes_match = hashes.get(filename, "") == example_hash

        if hashes_match and os.path.exists(image_file):
            print("-> using cached {}".format(image_file))
        else:
            # the file changed or the image file does not exist. Generate it.
            print("-> saving {}".format(image_file))
            chart = eval_block(example["code"])
            try:
                chart.save(image_file)
                hashes[filename] = example_hash
            except ImportError:
                warnings.warn("Unable to save image: using generic image", stacklevel=1)
                create_generic_image(image_file)

            with open(hash_file, "w") as f:
                json.dump(hashes, f)

        if make_thumbnails:
            params = example.get("galleryParameters", {})
            if example["use_svg"]:
                # Thumbnail for SVG is identical to original image
                thumb_file = os.path.join(image_dir, example["name"] + "-thumb.svg")
                shutil.copyfile(image_file, thumb_file)
            else:
                thumb_file = os.path.join(image_dir, example["name"] + "-thumb.png")
                create_thumbnail(image_file, thumb_file, **params)

    # Save hashes so we know whether we need to re-generate plots
    with open(hash_file, "w") as f:
        json.dump(hashes, f)


def populate_examples(**kwds):
    """Iterate through Altair examples and extract code"""

    examples = sorted(iter_examples_arguments_syntax(), key=itemgetter("name"))
    method_examples = {x["name"]: x for x in iter_examples_methods_syntax()}

    for example in examples:
        docstring, category, code, lineno = get_docstring_and_rest(example["filename"])
        if example["name"] in method_examples.keys():
            _, _, method_code, _ = get_docstring_and_rest(
                method_examples[example["name"]]["filename"]
            )
        else:
            method_code = code
            code += (
                "# No channel encoding options are specified in this chart\n"
                "# so the code is the same as for the method-based syntax.\n"
            )
        example.update(kwds)
        if category is None:
            raise Exception(
                f"The example {example['name']} is not assigned to a category"
            )
        example.update(
            {
                "docstring": docstring,
                "title": docstring.strip().split("\n")[0],
                "code": code,
                "method_code": method_code,
                "category": category.title(),
                "lineno": lineno,
            }
        )

    return examples


class AltairMiniGalleryDirective(Directive):
    has_content = False

    option_spec = {
        "size": int,
        "names": str,
        "indices": lambda x: list(map(int, x.split())),
        "shuffle": flag,
        "seed": int,
        "titles": bool,
        "width": str,
    }

    def run(self):
        size = self.options.get("size", 15)
        names = [name.strip() for name in self.options.get("names", "").split(",")]
        indices = self.options.get("indices", [])
        shuffle = "shuffle" in self.options
        seed = self.options.get("seed", 42)
        titles = self.options.get("titles", False)
        width = self.options.get("width", None)

        env = self.state.document.settings.env
        app = env.app

        gallery_dir = app.builder.config.altair_gallery_dir

        examples = populate_examples()

        if names:
            if len(names) < size:
                raise ValueError(
                    "altair-minigallery: if names are specified, "
                    "the list must be at least as long as size."
                )
            mapping = {example["name"]: example for example in examples}
            examples = [mapping[name] for name in names]
        else:
            if indices:
                examples = [examples[i] for i in indices]
            if shuffle:
                random.seed(seed)
                random.shuffle(examples)
            if size:
                examples = examples[:size]

        include = MINIGALLERY_TEMPLATE.render(
            image_dir="/_static",
            gallery_dir=gallery_dir,
            examples=examples,
            titles=titles,
            width=width,
        )

        # parse and return documentation
        result = ViewList()
        for line in include.split("\n"):
            result.append(line, "<altair-minigallery>")
        node = nodes.paragraph()
        node.document = self.state.document
        nested_parse_with_titles(self.state, result, node)

        return node.children


def main(app):
    gallery_dir = app.builder.config.altair_gallery_dir
    target_dir = os.path.join(app.builder.srcdir, gallery_dir)
    image_dir = os.path.join(app.builder.srcdir, "_images")

    gallery_ref = app.builder.config.altair_gallery_ref
    gallery_title = app.builder.config.altair_gallery_title
    examples = populate_examples(gallery_ref=gallery_ref, code_below=True, strict=False)

    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    examples = sorted(examples, key=lambda x: x["title"])
    examples_toc = collections.OrderedDict(
        {
            "Simple Charts": [],
            "Bar Charts": [],
            "Line Charts": [],
            "Area Charts": [],
            "Circular Plots": [],
            "Scatter Plots": [],
            "Uncertainties And Trends": [],
            "Distributions": [],
            "Tables": [],
            "Maps": [],
            "Interactive Charts": [],
            "Advanced Calculations": [],
            "Case Studies": [],
        }
    )
    for d in examples:
        examples_toc[d["category"]].append(d)

    # Write the gallery index file
    with open(os.path.join(target_dir, "index.rst"), "w") as f:
        f.write(
            GALLERY_TEMPLATE.render(
                title=gallery_title,
                examples=examples_toc.items(),
                image_dir="/_static",
                gallery_ref=gallery_ref,
            )
        )

    # save the images to file
    save_example_pngs(examples, image_dir)

    # Write the individual example files
    for prev_ex, example, next_ex in prev_this_next(examples):
        if prev_ex:
            example["prev_ref"] = "gallery_{name}".format(**prev_ex)
        if next_ex:
            example["next_ref"] = "gallery_{name}".format(**next_ex)
        target_filename = os.path.join(target_dir, example["name"] + ".rst")
        with open(os.path.join(target_filename), "w", encoding="utf-8") as f:
            f.write(EXAMPLE_TEMPLATE.render(example))


def setup(app):
    app.connect("builder-inited", main)
    app.add_css_file("altair-gallery.css")
    app.add_config_value("altair_gallery_dir", "gallery", "env")
    app.add_config_value("altair_gallery_ref", "example-gallery", "env")
    app.add_config_value("altair_gallery_title", "Example Gallery", "env")
    app.add_directive_to_domain("py", "altair-minigallery", AltairMiniGalleryDirective)

sphinxext/altairgallery.py
diff --git a/doc/case_studies/exploring-weather.rst b/doc/case_studies/exploring-weather.rst
index 4b16bef2a..b041ba212 100644
--- a/doc/case_studies/exploring-weather.rst
+++ b/doc/case_studies/exploring-weather.rst
@@ -266,10 +266,3 @@ If you want to further customize your charts, you can refer to Altair's
 :ref:`api`.
 
 .. _Pandas: http://pandas.pydata.org/
-
-
-.. toctree::
-   :maxdepth: 1
-   :hidden:
-
-   self
diff --git a/doc/case_studies/index.rst b/doc/case_studies/index.rst
new file mode 100644
index 000000000..3c24761c6
--- /dev/null
+++ b/doc/case_studies/index.rst
@@ -0,0 +1,10 @@
+Tutorials
+---------
+
+These tutorials explore more advanced use cases than the gallery.
+
+.. toctree::
+   :hidden:
+
+   exploring-weather
+   numpy-tooltip-images
diff --git a/doc/case_studies/numpy-tooltip-images.rst b/doc/case_studies/numpy-tooltip-images.rst
new file mode 100644
index 000000000..786a4c8e8
--- /dev/null
+++ b/doc/case_studies/numpy-tooltip-images.rst
@@ -0,0 +1,204 @@
+.. _numpy-tooltip-imgs:
+
+Displaying Numpy Images in Tooltips
+-----------------------------------
+
+In this tutorial,
+you’ll learn how to display images stored as Numpy arrays
+in tooltips with any Altair chart.
+
+First,
+we create some example image arrays with blobs of different sizes.
+We measure the area of the blobs
+in order to have a quantitative measurement to plot.
+
+.. altair-plot::
+    :output: repr
+
+    import numpy as np
+    import pandas as pd
+    from scipy import ndimage as ndi
+
+    rng = np.random.default_rng([ord(c) for c in 'altair'])
+    n_rows = 200
+
+    def create_blobs(blob_shape, img_width=96, n_dim=2, sizes=[0.05, 0.1, 0.15]):
+        """Helper function to create blobs in the images"""
+        shape = tuple([img_width] * n_dim)
+        mask = np.zeros(shape)
+        points = (img_width * rng.random(n_dim)).astype(int)
+        mask[tuple(indices for indices in points)] = 1
+        if blob_shape == 'circle':
+            im = ndi.gaussian_filter(mask, sigma=rng.choice(sizes) * img_width)
+        elif blob_shape == 'square':
+            im = ndi.uniform_filter(mask, size=rng.choice(sizes) * img_width, mode='constant') * rng.normal(4, size=(img_width, img_width))
+        return im / im.max()
+
+    df = pd.DataFrame({
+        'image1': [create_blobs('circle') for _ in range(n_rows)],
+        'image2': [create_blobs('square', sizes=[0.3, 0.4, 0.5]) for _ in range(n_rows)],
+        'group': rng.choice(['a', 'b', 'c'], size=n_rows)
+    })
+    # Compute the area as the proportion of pixels above a threshold
+    df[['image1_area', 'image2_area']] = df[['image1', 'image2']].applymap(lambda x: (x > 0.4).mean())
+    df
+
+Next, we define the function
+that will convert the Numpy arrays to base64-encoded_ strings.
+This is a necessary step
+for the tooltip to recognize that the data
+is in the form of an image and render it appropriately.
+
+
+.. altair-plot::
+    :output: repr
+
+    from io import BytesIO
+    from PIL import Image, ImageDraw
+    import base64
+
+
+    def create_tooltip_image(df_row):
+        """Concatenate, rescale, and convert images to base64 strings."""
+        # Concatenate images to show together in the tooltip
+        # This can be skipped if only one image is to be displayed
+        img_gap = np.ones([df_row['image1'].shape[0], 10])  # 10 px white gap between imgs
+        img_arr = np.concatenate(
+            [
+                df_row['image1'],
+                img_gap,
+                df_row['image2']
+            ],
+            axis=1
+        )
+
+        # Create a PIL image from the array.
+        # Multiplying by 255 and recasting as uint8 for the images to occupy the entire supported instensity space from 0-255
+        img = Image.fromarray((255 * img_arr).astype('uint8'))
+
+        # Optional: Burn in labels as pixels in the images. Can be helpful to keep track of which image is which
+        ImageDraw.Draw(img).text((3, 0), 'im1', fill=255)
+        ImageDraw.Draw(img).text((3 + df_row['image1'].shape[1] + img_gap.shape[1], 0), 'im2', fill=255)
+
+        # Convert to base64 encoded image string that can be displayed in the tooltip
+        buffered = BytesIO()
+        img.save(buffered, format="PNG")
+        img_str = base64.b64encode(buffered.getvalue()).decode()
+        return f"data:image/png;base64,{img_str}"
+
+    # The column with the base64 image string must be called "image" in order for it to trigger the image rendering in the tooltip
+    df['image'] = df[['image1', 'image2']].apply(create_tooltip_image, axis=1)
+
+    # Dropping the image arrays since they are large an no longer needed
+    df_plot = df.drop(columns=['image1', 'image2'])
+    df_plot
+
+Now we are ready to create the charts that show the images as tooltips
+when the dots are hovered with the mouse.
+We can see that the large white blobs
+correspond to the higher area measurements
+as expected.
+
+.. altair-plot::
+    import altair as alt
+
+    # The random() function is used to jitter points in the x-direction
+    alt.Chart(df_plot, width=alt.Step(40)).mark_circle(xOffset=alt.expr('random() * 16 - 8')).encode(
+        x='group',
+        y=alt.Y(alt.repeat(), type='quantitative'),
+        tooltip=['image'],
+        color='group',
+    ).repeat(
+        ['image1_area', 'image2_area']
+    ).resolve_scale(
+        y='shared'
+    ).properties(
+        title='Comparison of blob areas'
+    )
+
+Note that when including images as part of the chart data,
+the chart size often increases several-fold.
+The size of the chart above would have been 19 Kb without the images,
+but with the images added it is 760 Kb.
+While this is a 20x size increase,
+the base64 encoding is still quite storage efficient;
+if we would have included the images in their original Numpy array format
+the chart size would have been 35Mb!
+
+If we want to have even more fun and get a bit more sophisticated,
+we could show one chart at a time
+and update what is shown on the y-axis
+as well as what is shown in the image tooltip
+based on a dropdown selector.
+We start by defining a tooltip that only contains a single image
+instead of both the images concatenated together.
+
+.. altair-plot::
+    :output: repr
+
+    def create_tooltip_image(img_arr):
+        """Rescale and convert an image to a base64 string."""
+        # print(img_arr)
+        # Create a PIL image from the array.
+        # Multiplying by 255 and recasting as uint8 for the images to occupy the entire supported instensity space from 0-255
+        img = Image.fromarray((255 * img_arr).astype('uint8'))
+
+        # Convert to base64 encoded image string that can be displayed in the tooltip
+        buffered = BytesIO()
+        img.save(buffered, format="PNG")
+        img_str = base64.b64encode(buffered.getvalue()).decode()
+        return f"data:image/png;base64,{img_str}"
+
+    # The column with the base64 image string must be called "image" in order for it to trigger the image rendering in the tooltip
+    df[['image1_base64', 'image2_base64']] = df[['image1', 'image2']].applymap(create_tooltip_image)
+    # Dropping the image arrays since they are large an no longer needed
+    # Also drop the previous tooltip image for clarity
+    df_plot = df.drop(columns=['image1', 'image2', 'image'])
+    df_plot
+
+In our chart,
+we need to use a transform to update
+both the y-axis column as well as the tooltip column
+dynamically based on the selection in the dropdown.
+The comments in the code explain more in detail what each line
+in this chart specification does.
+
+.. altair-plot::
+    metric_dropdown = alt.binding_select(
+        options=['image1_area', 'image2_area'],
+        name='Image metric '
+    )
+    metric_param = alt.param(
+        value='image1_area',
+        bind=metric_dropdown
+    )
+    alt.hconcat(
+        # This first chart is the axis title and is only needed because
+        # Vega-Lite does not yet support passing an expression directly to the axis title
+        alt.Chart().mark_text(angle=270, dx=-150, fontWeight='bold').encode(
+            alt.TextValue(alt.expr(f'{metric_param.name}'))
+        ),
+        alt.Chart(df_plot, width=alt.Step(40)).mark_circle(xOffset=alt.expr('random() * 16 - 8')).encode(
+            x='group',
+            y=alt.Y('image_area:Q').title(''),
+            tooltip=['image:N'],
+            color='group',
+        ).properties(
+            title='Area of blobs'
+        ).transform_calculate(
+            # This first line updates the image_area which is used for the y axis
+            # to correspond to the selected string in the dropdown
+            image_area=f'datum[{metric_param.name}]',
+            # Since altair needs the tooltip field to be called `image`, we need to dynamically
+            # change what's in the `image` field depending on the selection in the dropdown
+            # This is further complicated by the fact that the string in the dropdown is not
+            # an exact match for the column holding the image data so we need
+            # to replace part of the name to match to match the corresponding base 64 image field
+            image=f'datum[replace({metric_param.name}, "_area", "_base64")]',
+        )
+    ).add_params(
+        metric_param
+    )
+
+
+.. _base64-encoded: https://en.wikipedia.org/wiki/Binary-to-text_encoding
diff --git a/pyproject.toml b/pyproject.toml
index 652ecbe16..4def443b6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -86,6 +86,7 @@ doc = [
     "myst-parser",
     "sphinx_copybutton",
     "sphinx-design",
+    "scipy",
 ]
 
 [tool.hatch.version]
diff --git a/sphinxext/altairgallery.py b/sphinxext/altairgallery.py
index 94f4066aa..f76805c90 100644
--- a/sphinxext/altairgallery.py
+++ b/sphinxext/altairgallery.py
@@ -86,7 +86,7 @@
    :hidden:
 
    Gallery <self>
-   Tutorials <../case_studies/exploring-weather>
+   Tutorials <../case_studies/index>
 """
 )
 

Add example showing how to render numpy image arrays as tooltip images
I think it could be helpful to show how images that are represented as numpy arrays can be rendered in tooltips in altair. I can add a doc example of this. Maybe in [the tutorials/case studies](https://altair-viz.github.io/case_studies/exploring-weather.html) section? We only have one example there currently. Another option would be to combine it with https://altair-viz.github.io/gallery/image_tooltip.html and create a new page in the user guide on images, but that 's more involved.

Here is the code and a video of the output. Note that this would add scipy as a documentation dependency (I could probably get around that, but I have another example I want to add that requires scipy so thought I might as well ask now if it is ok to add it). The images are not too large, the size of the chart saved as an html file is around 200kb.

1. Create some example image arrays with blobs in them and measure the area of the blobs.
    ```python
    import numpy as np
    import pandas as pd
    from scipy import ndimage as ndi
    
    rng = np.random.default_rng([ord(c) for c in 'altair'])
    n_rows = 200
    
    def create_blobs(img_width=96, n_dim=2, thresh=0.0001, sigmas=[0.1, 0.2, 0.3]):
        """Helper function to create blobs in the images"""
        shape = tuple([img_width] * n_dim)
        mask = np.zeros(shape)
        points = (img_width * rng.random(n_dim)).astype(int)
        mask[tuple(indices for indices in points)] = 1
        return ndi.gaussian_filter(mask, sigma=rng.choice(sigmas) * img_width) > thresh
    
    df = pd.DataFrame({
        'img1': [create_blobs() for _ in range(n_rows)],
        'img2': [create_blobs(sigmas=[0.15, 0.25, 0.35]) for _ in range(n_rows)],
        'group': rng.choice(['a', 'b', 'c'], size=n_rows)
    })
    df[['img1_area', 'img2_area']] = df[['img1', 'img2']].applymap(np.mean)
    df
    ```

2. Convert the numpy arrays to base64 encoded strings that will show in the tooltip

    ```python
    from io import BytesIO
    from PIL import Image, ImageDraw
    import base64
    
    
    def create_tooltip_image(df_row):
        # Concatenate images to show together in the tooltip
        img_gap = np.ones([df_row['img1'].shape[0], 10])  # 10 px white gap between imgs
        img = Image.fromarray(
            np.concatenate(
                [
                    df_row['img1'] * 128,  # grey
                    img_gap * 255,  # white
                    df_row['img2'] * 128
                ],
                axis=1
            ).astype('uint8')
        )
        
        # Optional: Burn in labels as pixels in the images
        ImageDraw.Draw(img).text((3, 0), 'img1', fill=255)
        ImageDraw.Draw(img).text((3 + df_row['img1'].shape[1] + img_gap.shape[1], 0), 'img2', fill=255)
        
        # Convert to base64 encoded image string that can be displayed in the tooltip
        buffered = BytesIO()
        img.save(buffered, format="PNG")
        img_str = base64.b64encode(buffered.getvalue()).decode()
        return f"data:image/png;base64,{img_str}"
    
    # The column with the image must be called "image" in order for it to trigger the image rendering in the tooltip
    df['image'] = df[['img1', 'img2']].apply(create_tooltip_image, axis=1)
    
    # Dropping the images since they are large an no longer needed
    df = df.drop(columns=['img1', 'img2'])
    df
    ```
3. Create a chart to show the images


    ```python
    import altair as alt
    
    alt.Chart(df, title='Area of grey blobs').mark_circle().encode(
        x='group',
        y=alt.Y(alt.repeat(), type='quantitative'),
        tooltip=['image'],
        color='group'
    ).repeat(
        ['img1_area', 'img2_area']
    )
    ```


https://github.com/altair-viz/altair/assets/4560057/45ccc43f-c8a4-4b3b-bb42-ed0b18cd9703


