🤓 Scikit-plots Examples & Tutorials
0.5.dev0+git.20260824.c8953a1 - August 24, 2026 15:07 UTC

Examples#

This is the gallery of examples that showcase how scikit-plots can be used. Some examples demonstrate the use of the APIs Reference in general and some demonstrate specific applications in tutorial form. Also check out our user guide for more detailed illustrations.

This page contains example plots. Click on any image to see the full image and source code.

Tagging!

You can also browse the example gallery by tags.

Jupyter Notebooks#

See also

🚀 Try Scikit-Plots in Your Browser with Notebooks

No installation required. Launch one of the interactive environments below.

jupyterlite (pyodide, xeus-python, c, c++)

jupyterlite lab pyodide:

jupyterlite lab all-in-one-pyodide[pyodide, xpython, r, c, cpp, sqlite, js, p5]:

jupyterlite lab all-in-one-xeus[xpython, r, c, cpp, js]:

jupyterlite lab terminal[pyodide]:

jupyterlite lab misc:

Annoy#

Examples for annoy cover approximate nearest-neighbor index construction, querying, persistence, memory mapping, precision trade-offs, and lower-level native/Cython interfaces.

The gallery intentionally contains several API layers. Most users should start with the public Python Index interface and move to the lower layers only when they need dtype/native compatibility or implementation-level benchmarking.

Start here: ANNoy Vector Index DB#

1. Simple nearest-neighbor search

Start with plot_simple_script.py.

It demonstrates the shortest useful workflow:

from scikitplot.annoy import Index

index = Index(
    f=3,
    metric="angular",
)

index.add_item(0, [1, 0, 0])
index.add_item(1, [0, 1, 0])
index.add_item(2, [0, 0, 1])

index.build(-1)

print(index.get_nns_by_item(0, 10))
print(index.get_nns_by_vector([1.0, 0.5, 0.5], 10))

Use this page to understand the core lifecycle before looking at persistence, Cython, legacy, or benchmark examples.

Choose the right API layer#

The gallery contains three distinct layers.

Layer

Typical import

Use when

Public Python API

from scikitplot.annoy import Index

normal application code and new examples

Cython/native API

from scikitplot.annoy._annoy import Index

dtype/native experiments, implementation-level testing

Legacy C-extension API

scikitplot.cexternals._annoy

compatibility testing and migration work

Prefer the public Python API unless the example is specifically teaching a lower-level contract.

Private/internal imports in the advanced examples are deliberate teaching or maintenance surfaces; they should not be copied into ordinary application code without understanding their compatibility implications.

Core index lifecycle#

The common Annoy lifecycle is:

vectors
   ↓
Index(f, metric)
   ↓
add_item(...)
   ↓
build(n_trees)
   ↓
query
  ├── get_nns_by_item(...)
  └── get_nns_by_vector(...)
   ↓
optional save(...)
   ↓
optional load(...) / mmap-backed querying

Build parameters affect index construction, while query parameters affect the search work performed against an already-built index.

Metrics#

Examples use several supported metric families, including:

angular

cosine-like angular distance for directional similarity.

euclidean

L2 distance.

manhattan

L1 distance.

dot

dot-product-oriented similarity.

hamming

Hamming-distance-oriented indexing where supported by the selected native type combination.

Not every dtype/metric/native combination should be assumed equivalent. Use the public API defaults for ordinary applications and the Cython examples when explicitly investigating concrete type combinations.

Persistence and memory mapping#

plot_mmap_script.py demonstrates the persistent workflow:

index.save("example.annoy")

restored = Index(
    f=3,
    metric="angular",
)
restored.load("example.annoy")

Annoy indexes are designed to support file-backed querying. Keep the vector dimension and metric consistent with the index that was written.

Treat bundled .annoy / .tree files in this gallery as example/test artifacts, not as a stable cross-version interchange format unless the relevant compatibility contract has been explicitly verified.

Precision and benchmark examples#

The precision and benchmark pages are not beginner tutorials.

They may:

  • generate many random vectors,

  • build many trees,

  • exercise multiple dtype/metric combinations,

  • launch subprocesses or pytest benchmarks,

  • write index artifacts,

  • consume substantially more CPU, memory, or disk than the simple example.

Use them for engineering comparison, regression testing, or capacity planning. Do not infer production sizing from a single gallery benchmark.

Hamlet Cython showcase#

plot_annoy_cython_hamlet_example.py is the broadest Annoy demonstration.

It uses a real text corpus, converts passages to vectors, and compares native Annoy behavior across advanced configurations.

Conceptually:

Hamlet passages
    ↓
text vectorization
    ↓
native Annoy Index
    ↓
dtype / metric variants
    ↓
nearest-neighbor search
    ↓
build-time / size / retrieval comparison

Use it after the public Python examples. It is a showcase of the lower-level native implementation surface, not the minimum API required to use Annoy.

Native capability#

Annoy in scikit-plots includes compiled/native components. A gallery or CI environment may therefore have the Python package available while a required native implementation is unavailable for that platform/build.

The desired gallery rule is:

native Annoy capability unavailable

Report a specific SKIP when the example cannot truthfully continue.

native Annoy imports successfully but build/query fails

Fail visibly. Do not convert an installed-backend regression into a skip.

The same distinction applies to compiler-dependent benchmark examples.

Files and working directories#

Several historical/advanced examples read or write artifacts such as:

*.annoy
*.tree
*.npy
*.csv
*.joblib

New examples should prefer a temporary directory or a path derived from the example location rather than relying on the caller’s current working directory.

Gallery examples should not overwrite repository test fixtures merely to demonstrate persistence.

Reproducibility#

For deterministic examples:

  • seed random-number generators where random vectors are generated,

  • keep dimensions and item counts bounded,

  • print bounded result summaries,

  • separate correctness checks from performance measurements,

  • record the metric, number of trees, and query parameters used for benchmark comparisons.

Approximate nearest-neighbor results can depend on build/search configuration; benchmark pages should make those parameters visible.

Relationship to Corpus and MCP#

Annoy can also be used as a retrieval backend by higher-level scikit-plots components.

For document retrieval:

scikitplot.corpus
    ↓
document embeddings
    ↓
Annoy vector backend
    ↓
retrieval

For a protocol/server workflow:

Corpus
  ↓
Annoy
  ↓
CorpusAnnoyRetriever
  ↓
scikitplot.mcp

Use the Corpus/MCP galleries when the goal is document ingestion or MCP serving. Use this Annoy gallery when the goal is understanding and validating the vector index itself.

CI guidance#

A practical CI split is:

Portable/public API gate

Run the small public Python examples and focused Annoy tests.

Native capability gate

Run Cython/native examples only on environments that intentionally provide the required compiled extension.

Benchmark gate

Keep expensive dtype/precision/compiler benchmarks separate from the normal documentation build when they materially increase build time or resource consumption.

An unavailable optional native/compiler capability should be reported explicitly. Security, serialization, index-corruption, or installed-backend failures should remain visible.

Browser / WASM note#

Do not assume that the native Annoy implementation, memory mapping, filesystem semantics, subprocesses, or C/C++ compiler examples are available in JupyterLite/Pyodide/other browser-WASM runtimes.

Use the simple/public API examples there only when the relevant native package has been explicitly built and verified for that runtime.

The Cython, mmap, compiler, and benchmark pages should otherwise be treated as reference material in browser environments.

Array API support#

Examples related to the _lib submodule with e.g. LogisticRegression instance.

Calibration#

Examples related to the metrics submodule with e.g. LogisticRegression instance.

plot_calibration with examples

plot_calibration with examples

Classification#

Examples related to the estimators submodule with e.g. LogisticRegression instance.

plot_classifier_eval with examples

plot_classifier_eval with examples

plot_confusion_matrix with examples

plot_confusion_matrix with examples

plot_feature_importances with examples

plot_feature_importances with examples

plot_learning_curve with examples

plot_learning_curve with examples

plot_precision_recall with examples

plot_precision_recall with examples

plot_roc_curve with examples

plot_roc_curve with examples

Clustering#

Examples related to the estimators submodule with e.g. LogisticRegression instance.

plot_elbow with examples

plot_elbow with examples

plot_silhouette with examples

plot_silhouette with examples

Corpus#

Examples for corpus are ordered as a learning path rather than by implementation detail.

# 💡 corpus Need additionals packages
curl -O https://raw.githubusercontent.com/scikit-plots/scikit-plots/main/requirements/corpus.txt
pip install -r requirements/corpus.txt
pip install scikit-plots[corpus]

# (Recommended)
# !pip install datasets transformers
# !pip install nltk gensim langdetect faster-whisper openai-whisper pytesseract youtube-transcript-api
# sudo apt-get install tesseract-ocr

Start here#

  1. Configure Corpus declaratively — learn FluentCorpus, immutable plans, validation, branching, fingerprints, and the materialize() boundary.

  2. Build and search a real Hamlet corpus — use RuntimeCorpus end to end: run(), add(), storage, retrieval, export, and lifecycle.

  3. Compare chunking strategies — compare sentence, word, fixed-window, and morphological semantic chunking on the same OCR text.

  4. Process an MP3 — learn audio provenance and companion-transcript precedence without requiring Whisper in the normal gallery path.

  5. Process a mixed-media ZIP — inspect archive-member routing, archive.zip/member.ext provenance, and per-extension reader settings.

  6. Process a YouTube transcript — execute a deterministic local proxy, configure the real YouTube reader, and keep the live transcript request explicit and optional.

  7. Build a multi-source WHO corpus — see the explicit stage-by-stage integration path, partial source success, keyword retrieval, adapters, and where CorpusBuilder fits.

Which API should I use?#

Goal

Start with

Process one source with direct stage control

CorpusPipeline

Build/search heterogeneous sources with partial-success reporting

CorpusBuilder

Create immutable, reusable, branchable configuration

FluentCorpus

Execute a Fluent plan and manage runtime state/lifecycle

RuntimeCorpus

Extend vector indexing/retrieval directly

RetrievalIndex / VectorIndexBackend

Capability matrix#

The normal gallery path prefers deterministic local execution. Optional capabilities are either preflighted and skipped when unavailable, or shown as configuration-only examples.

Example

Normal path

Optional capability

Behavior when unavailable

FluentCorpus basics

local/core

none

not applicable

Hamlet RuntimeCorpus

local/core + NumPy

native Annoy branch

configuration only; not built

OCR chunking comparison

local image

Tesseract, NLTK

explicit SKIP for unavailable capability

MP3 ingestion

MP3 + local SRT companion

NLTK, Whisper

optional sections SKIP

Mixed-media ZIP

local archive

PDF/OCR/Whisper readers

individual optional member capability may produce no documents; archive-security failures still fail

YouTube transcript

local synthetic proxy

youtube-transcript-api + network, NLTK

live/optional sections SKIP

WHO multi-source integration

local sidecars only

PDF/OCR/Whisper

each unavailable source reports SKIP; successful evidence remains

Gallery reliability rule#

The examples distinguish optional capability absence from real defects:

missing optional package/resource/native capability/network opt-in

Report a visible, specific SKIP and continue when the example can remain truthful.

invalid public API / security-policy failure / installed-backend defect

Fail visibly. The gallery must not convert a real regression into a skip.

A missing local sidecar never silently enables public-network access.

Install only what you need#

The core text/runtime examples use the normal Corpus installation. Media and NLP examples may additionally use packages such as NLTK, an OCR backend, Whisper, or youtube-transcript-api. System tools such as Tesseract may also be required for the corresponding optional path.

Do not install every optional dependency merely to read the gallery. The portable path is designed to remain useful when those capabilities are absent.

Browser / WASM note#

Declarative configuration, local text processing, and portable brute-force retrieval are the strongest browser/WASM candidates. OCR, Whisper, native ANN backends, and live external services depend on the actual JupyterLite/xeus runtime and should not be assumed available until verified in that target environment.

Process an MP3 with Corpus

Process an MP3 with Corpus

Configure Corpus with FluentCorpus

Configure Corpus with FluentCorpus

Build and Search a Real Hamlet Corpus with FluentCorpus

Build and Search a Real Hamlet Corpus with FluentCorpus

Build and Search a Real Hamlet Corpus with FluentCorpus

Build and Search a Real Hamlet Corpus with FluentCorpus

Build and Search a Real Hamlet Corpus with FluentCorpus

Build and Search a Real Hamlet Corpus with FluentCorpus

Compare Corpus Chunking Strategies on OCR Text

Compare Corpus Chunking Strategies on OCR Text

Build a Multi-Source WHO Corpus

Build a Multi-Source WHO Corpus

Process a YouTube Transcript with Corpus

Process a YouTube Transcript with Corpus

Process a Mixed-Media ZIP Archive with Corpus

Process a Mixed-Media ZIP Archive with Corpus

Cython#

Examples related to the cython submodule.

# 💡cython Need cython and setuptools
pip install scikitplot[build] setuptools

# (Recommended)
# !pip install cython setuptools

Cython quickstart: compile_and_load

Cython quickstart: compile_and_load

Browse and compile templates

Browse and compile templates

Build profiles: fast-debug, release, annotate

Build profiles: fast-debug, release, annotate

Cache and restart reuse

Cache and restart reuse

Pin/Alias: stable handles for cached builds

Pin/Alias: stable handles for cached builds

Multi-module package builds (5 package examples)

Multi-module package builds (5 package examples)

Multi-file builds: .pxi includes and external headers

Multi-file builds: .pxi includes and external headers

C++ mode basics: cppclass and libcpp containers

C++ mode basics: cppclass and libcpp containers

Vector ops without NumPy: array(‘d’) + memoryviews

Vector ops without NumPy: array('d') + memoryviews

Workflow templates (train / hpo / predict) + CLI entry template

Workflow templates (train / hpo / predict) + CLI entry template

Cython: Realtime compile_and_load (.pyx)

Cython: Realtime compile_and_load (.pyx)

Decile#

Examples related to the decile submodule with e.g. LogisticRegression instance.

See also

  • Seaborn-style decile analysis (Lift / Gain / KS) decileplot

plot_cumulative_gain with examples

plot_cumulative_gain with examples

plot_ks_statistic with examples

plot_ks_statistic with examples

plot_lift with examples

plot_lift with examples

Introduction to modelplotpy (legacy)

Introduction to modelplotpy (legacy)

Introduction to modelplotpy

Introduction to modelplotpy

plot_report with examples

plot_report with examples

Decomposition#

Examples related to the decomposition submodule with e.g. PCA instance.

plot_pca_2d_projection with examples

plot_pca_2d_projection with examples

plot_pca_component_variance with examples

plot_pca_component_variance with examples

Impute#

Examples related to the impute submodule with a scikit-learn regressor (e.g., LinearRegression) instance.

# 💡impute may need voyager
pip install scikitplot[core]

# (Optionally)
# !pip install voyager

annoy impute with examples

annoy impute with examples

Mcp#

Examples for mcp focus on exposing local scikit-plots evidence through a small, read-only Model Context Protocol (MCP) surface.

The current showcase connects three public submodules:

scikitplot.corpus

builds deterministic local evidence with HAMLET_TEXT and HashEmbedder.

scikitplot.annoy

provides the optional native approximate-nearest-neighbor backend.

scikitplot.mcp

serves the indexed evidence through search_docs and docs://chunk/{doc_id}.

# MCP server/client dependencies
pip install scikit-plots[mcp]

# Verify the centralized CLI
scikitplot mcp --help

Start here#

Serve a real Hamlet corpus over MCP with Annoy

The showcase follows one complete local workflow:

HAMLET_TEXT
    ↓
local corpus directory
    ↓
HashEmbedder
    ↓
Annoy
    ↓
CorpusAnnoyRetriever
    ↓
scikitplot mcp --self-test
    ↓
scikitplot mcp --docker
    ↓
MCP client context
    ↓
search_docs(...)
    ↓
citations + docs://chunk/{doc_id}

It is intentionally built from local data so the retrieval result does not depend on a model download or an external document service.

Execution layers#

The example separates increasingly optional capabilities instead of requiring the full server stack for every documentation build.

Layer

Requires

Normal purpose

If unavailable

Hamlet corpus

Corpus core

create local evidence

runs normally

Hash embedding

NumPy / Corpus core

deterministic document/query vectors

runs normally

Corpus + Annoy retrieval

native scikitplot.annoy

real ANN search

specific SKIP

CLI --self-test

Corpus + Annoy

verify backend without opening a server

specific SKIP when Annoy is absent

MCP HTTP server

MCP server dependencies

expose tools/resources

specific SKIP

MCP client round trip

MCP SDK + local server

verify the real protocol boundary

run only in provisioned CI/manual environments

CLI self-test first#

Before opening a listening server, validate the exact Corpus + Annoy configuration with the bounded CLI self-test:

scikitplot mcp \
    --corpus-annoy /tmp/scikitplot-mcp-hamlet \
    --hash-dimension 256 \
    --annoy-n-trees 10 \
    --self-test \
    --self-test-query "sleep dream death" \
    --self-test-require-match

This is the preferred first CI gate because it verifies corpus loading, embedding, index construction, querying, and the MCP result contract without requiring an HTTP client/server round trip.

Two-terminal server workflow#

Terminal 1 — server

scikitplot mcp --docker \
    --host 127.0.0.1 \
    --corpus-annoy /tmp/scikitplot-mcp-hamlet \
    --hash-dimension 256 \
    --annoy-n-trees 10

Terminal 2 — client

from mcp import Client

async with Client("http://127.0.0.1:8000/mcp") as client:
    result = await client.call_tool(
        "search_docs",
        {
            "query": "sleep dream death",
            "k": 3,
        },
    )

print(result.structured_content)

The showcase also polls /healthz before creating the client and always terminates the server subprocess during cleanup.

CI / documentation mode#

For an ordinary documentation build, keep the live HTTP round trip disabled:

export SCIKITPLOT_GALLERY_RUN_MCP_DOCKER=0

To execute the full local server/client round trip in a provisioned CI container:

export SCIKITPLOT_GALLERY_RUN_MCP_DOCKER=1
python galleries/examples/mcp/plot_mcp_corpus_annoy_hamlet_script.py

The CI subprocess explicitly binds to 127.0.0.1. This keeps the unauthenticated showcase server on loopback rather than exposing it beyond the container/host merely to test the protocol path.

What --docker means here#

The example invokes:

scikitplot mcp --docker ...

through Python’s subprocess module.

It is the scikit-plots MCP server’s Docker-oriented runtime profile; the Python gallery itself is not a replacement for docker run or container orchestration. The same command can be launched inside your normal CI/Docker environment.

Gallery reliability rule#

The MCP examples use the same reliability distinction as the Corpus gallery:

missing optional native Annoy / MCP SDK / intentionally disabled live server

Report a visible, specific SKIP when the remaining example can stay truthful.

invalid public API / broken installed backend / malformed MCP result / server crash

Fail visibly. Do not convert a real integration regression into a skip.

The local deterministic path must never fabricate Annoy or MCP success when those capabilities were not actually exercised.

Security and lifecycle#

The showcase is read-only and uses bounded result previews.

For automated server execution it also:

  • chooses a free loopback port,

  • waits for /healthz before connecting,

  • binds explicitly to 127.0.0.1,

  • terminates the child process in a finally/context cleanup path,

  • escalates to kill() only if graceful termination exceeds the timeout.

Treat wider network exposure, authentication, reverse proxies, TLS, and production process supervision as deployment concerns rather than gallery defaults.

Browser / WASM note#

The deterministic Corpus and hashing pieces are portable Python/NumPy candidates. Native Annoy, subprocess management, listening sockets, and a real MCP HTTP server should not be assumed available in JupyterLite or other browser/WASM runtimes.

Use the gallery there as architecture/reference material unless those runtime capabilities have been explicitly verified.

Serve a Real Hamlet Corpus over MCP with Annoy

Serve a Real Hamlet Corpus over MCP with Annoy

MemMap#

Examples related to the memmap submodule.

Memory-Mapping Showcase – Basic / Medium / Advanced

Memory-Mapping Showcase – Basic / Medium / Advanced

Misc#

Examples related to the misc submodule.

Misc Showcase

Misc Showcase

MLflow#

Examples related to the mlflow submodule with a scikit-learn regressor (e.g., LinearRegression) instance.

# 💡mlflow Need mlflow
pip install scikitplot[mlflow]

# (Recommended)
# !pip install mlflow

MLflow

MLflow

Nc (NumCpp)#

Examples related to the nc submodule.

nc with examples

nc with examples

Preprocessing#

Examples related to the preprocessing submodule with e.g., DummyCodeEncoder, GetDummies instance.

Comparing DummyCode Encoder with Other Encoders

Comparing DummyCode Encoder with Other Encoders

Random#

Examples related to the random submodule.

Enhanced KISS Random Generator - Complete Usage Examples

Enhanced KISS Random Generator - Complete Usage Examples

Regression#

Examples related to the metrics submodule with e.g., LinearRegression instance.

plot_residuals_distribution with examples

plot_residuals_distribution with examples

Seaborn#

Examples related to the seaborn submodule with a scikit-learn regressor (e.g., LinearRegression) instance.

plot_aucplot_script with examples

plot_aucplot_script with examples

plot_decileplot_script with examples

plot_decileplot_script with examples

plot_evalplot_script with examples

plot_evalplot_script with examples

Stats#

Examples related to the stats submodule with e.g. LinearRegression instance.

Gaussian Mixture Models — AIC, AICc, and BIC Model Selection

Gaussian Mixture Models — AIC, AICc, and BIC Model Selection

plot_residuals_distribution with examples

plot_residuals_distribution with examples

Visualkeras#

Examples related to the visualkeras submodule with e.g. a DL (ANN, CNN, NLP) tf.keras.Model model instance.

Important

# 💡visualkeras Need aggdraw tensorflow or tensorflow-cpu
pip install scikitplot[core, cpu]

# (Recommended)
# !pip install aggdraw
# !pip install tensorflow

python -c "import tensorflow as tf, google.protobuf as pb; print('tf', tf.__version__); print('protobuf', pb.__version__)"
python -m pip check

# If Needed
# pip install -U "protobuf<6"
# pip install protobuf==5.29.4
import tensorflow as tf

Visualkeras: Spam Classification Conv1D Dense Example

Visualkeras: Spam Classification Conv1D Dense Example

visualkeras: Spam Dense example

visualkeras: Spam Dense example

visualkeras: autoencoder example

visualkeras: autoencoder example

visualkeras: custom vgg16 example

visualkeras: custom vgg16 example

visualkeras: custom vgg16 show dimension example

visualkeras: custom vgg16 show dimension example

visualkeras: EfficientNetV2 example

visualkeras: EfficientNetV2 example

visualkeras: ResNetV2 example

visualkeras: ResNetV2 example

visualkeras: custom VGG example

visualkeras: custom VGG example

visualkeras: Vector Index DB

visualkeras: Vector Index DB

Gallery generated by Sphinx-Gallery