🐈
sphinxのドキュメントにaltairのプロットを埋め込む
はじめに
動的にSphinxでレポート作成する際、Altairで生成した動的なFigを埋め込む方法について簡単に説明します。
やること
- 環境構築
- 適当なSphinxプロジェクトの作成
- Altairでhtml出力でfigを生成
- Sphinxにiframeで埋め込み
環境構築
sphinxの実行コンテナ定義ファイルとしてsphinxdoc.defをrecipeフォルダに配置します。
sphinxdoc.def
Bootstrap: docker
From: debian:bookworm-slim
%labels
Version 1.0.0
Description "Debian-based image with Sphinx, themes, and Altair (uv-managed venv)"
%post
set -e
export DEBIAN_FRONTEND=noninteractive
# Base tools and Python
apt-get update && apt-get install -y --no-install-recommends \
python3 \
python3-venv \
python3-pip \
build-essential \
git \
make \
ca-certificates \
curl
rm -rf /var/lib/apt/lists/*
# Install uv (Python package manager)
export UV_INSTALL_DIR=/usr/local/bin
curl -LsSf https://astral.sh/uv/install.sh | sh
# Create an isolated virtual environment for docs
uv venv /opt/venv
# Python packages for documentation, themes, and visualization
uv pip install --python /opt/venv/bin/python \
sphinx \
sphinxawesome-theme \
myst-parser \
sphinx-autobuild \
sphinx-copybutton \
altair \
vega-datasets \
typer \
jinja2 \
pyyaml
%environment
export VIRTUAL_ENV=/opt/venv
export PATH=/opt/venv/bin:/usr/local/bin:$PATH
export PYTHONUNBUFFERED=1
export LC_ALL=C.UTF-8
export PIP_DISABLE_PIP_VERSION_CHECK=1
%runscript
exec "$@"
続いて、カレントディレレクトリにcontainerフォルダを作成しててコンテナファイルを出力します。
singularity build container/sphinxdoc.sif recipec/sphinxdoc.def
適当なSphinxプロジェクトの作成
次に、sphinx-quickstartを使用してプロジェクトフォルダを作成します。
./container/sphinxdoc.sif sphinx-quickstart docs -q \
-p "Altair Sphinx Demo" \
-a "Your Name" \
-v "0.1"
tree docs
docs
├── Makefile
├── _build
├── _static
├── _templates
├── conf.py
├── index.rst
└── make.bat
3 directories, 4 files
Altairでhtml出力のFig生成
AltairでFigを生成するmake_altair_plot.pyをscriptsフォルダに配置します。
make_altair_plot.py
# make_altair_plot.py
from pathlib import Path
import altair as alt
import typer
from vega_datasets import data
app = typer.Typer(help="Altair chart generator for Sphinx docs")
@app.command()
def main(
output: Path = typer.Option(
Path("docs/_static/altair_example.html"),
"--output",
"-o",
help="出力するHTMLファイルのパス(Sphinx の _static 配下を推奨)",
)
):
"""
Altair のインタラクティブなチャートを HTML として保存します。
"""
cars = data.cars()
chart = (
alt.Chart(cars)
.mark_point()
.encode(
x="Horsepower",
y="Miles_per_Gallon",
color="Origin",
tooltip=["Name", "Horsepower", "Miles_per_Gallon", "Origin"],
)
.properties(title="Altair + Sphinx demo")
)
html = chart.to_html(
embed_options={
"actions": True,
"renderer": "canvas",
"responsive": True,
}
)
with open(f"{output}", mode="w") as f:
f.write(html)
typer.echo(f"Saved: {output}")
if __name__ == "__main__":
app()
準備が出来たら実行してFigを生成。
singularity exec container/sphinxdoc.sif python scripts/make_altair_plot.py --output docs/_static/my_altair_plot.html
# Saved: docs/_static/my_altair_plot.html
docs/_staticフォルダにmy_altair_plot.htmlが生成されているはずです。
Sphinx のページに埋め込む
docs/index.rst を開いて、内容をこんな感じに編集します。srcに先ほど作成したhtmlファイルをdocs/index.rstをベースとした相対パスで記載します。
.. Altair Sphinx Demo documentation master file, created by
sphinx-quickstart on Sun Nov 30 03:37:07 2025.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to Altair Sphinx Demo
=============================
これは Altair のインタラクティブなグラフを Sphinx ドキュメントに
iframe で埋め込むテストページです。
Altair plot
-----------
.. raw:: html
<iframe
src="_static/my_altair_plot.html"
style="border:none; width: 100%; height: 500px;"
></iframe>
-
.. raw:: htmlの中に素のHTMLを書いてiframeで読み込んでいます。 - パスは
my_altair_plot.htmlを指定
Sphinx themeの変更
docs/conf.pyのhtml_themeをデフォルトからsphinxawesome_themeに変更しています。
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = "Altair Sphinx Demo"
copyright = "2025, Your Name"
author = "Your Name"
version = "0.1"
release = "0.1"
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = []
templates_path = ["_templates"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = "sphinxawesome_theme"
html_static_path = ["_static"]
# language
locale_dirs = ['locale/']
gettext_compact = False
language = "ja"
Figの出力
singularity exec container/sphinxdoc.sif python scripts/make_altair_plot.py --output docs/_static/my_altair_plot.html
# Saved: docs/_static/my_altair_plot.html
Build
cd docs
singularity exec ../container/sphinxdoc.sif make html
_build/html/index.htmlをブラウザで開くと以下のようにAltairの散布図が表示されていることが確認できました。

その他 Sphinx関連パッケージ
今回、使用したテーマはawesomeにしました。Sphinxのテーマは下記リンク先のGallaryから使用するものを決めていいと思います。
Markdown・図表など「コンテンツ記法」系
UIコンポーネント・見た目をリッチにする系
i18n (多言語対応)
Sphinx同梱の代表的な拡張
外部パッケージではありませんが、conf.py の extensions に追加しておくと有用な「標準拡張」も挙げておきます。
おしまい。
Discussion