Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

SeraPlot

Plot anything. Train anything. Ship anywhere.

A Rust-native engine for visualization, machine learning, and zero-friction delivery — 6,000× faster than Plotly, 200× smaller, zero dependencies.

PyPI npm License

Seraplot, More than a charting library

SeraPlot is a complete data toolkit written in Rust. The same engine powers your visualizations, your machine learning, and the way you ship results to other people.

PillarWhat you get
Plot57 chart types — 33 in 2D, 17 in 3D (WebGL), 2 maps. Built-in themes, palettes, animation, zoom, crosshair, export.
TrainScikit-learn-compatible ML in Rust — DBSCAN, K-Means, RandomForest, GradientBoosting, SVM, PCA, GridSearchCV, train/test split. 1.3× to 686× faster.
Stream & scaleLive updates, downsampling for millions of points, drift detection, AutoML, diff mode, facet grids.
ShipSelf-contained 21 KB HTML — no CDN, no backend, works offline, by email, in S3, in PDFs, in Notion, in air-gapped CI.
IntegratePython, JavaScript, TypeScript, Rust. Drop-in seraplot.matplotlib as plt migration. Pandas / NumPy native.
AuthorNative VS Code extension — live preview, gallery, theme studio, snippets, auto-detection of labels / values from your code.
Persist & exportSave to HTML, PNG, SVG, PDF, pickle. Re-load trained ML models. CSP-safe output.
Stay accessibleA11y-tagged SVG, semantic HTML, keyboard navigation, locale-aware number formatting.

One library replaces: matplotlib + plotly + dash + streamlit + seaborn + parts of scikit-learn — with one pip install and zero runtime dependencies.


Same chart — three libraries

import seraplot as sp
sp.bar("Revenue by Product", labels, values).save("chart.html")
import plotly.express as px
fig = px.bar(x=labels, y=values, title="Revenue by Product")
fig.update_layout(template="plotly_white")
fig.write_html("chart.html")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(9, 5))
ax.bar(labels, values, color="#6366f1")
ax.set_title("Revenue by Product")
ax.set_ylabel("Revenue")
plt.tight_layout()
plt.savefig("chart.png")
SeraPlotPlotlyMatplotlib
Lines of code247
OutputHTMLHTMLPNG
File size21 KB4.7 MB~150 KB
Interactive
Dependencies06+3+
1-line migration

Why Seraplot?

As you’ve probably understood by now, Seraplot is a tool designed to be extremely customizable, while also being much faster and more resource-efficient than existing solutions. It also provides a wide range of helpful features, such as the Seraplot extension for VSCode, which allows you to generate plots or ML methods very quickly and live, between each save of your scripts.

In addition, Seraplot is available across multiple languages such as: JS/TS, C (C# & C++), Java, Rust, Python, R & Scala. The main goal is to be highly accessible: from one language to another, the commands remain the same for greater simplicity.

In summary, Seraplot is a much more practical and independent tool that enables the generation of 2D & 3D plots, while also aiming to provide machine learning-related methods that you will find throughout the documentation. More surprises await you, such as the ability to choose different themes, a chunk system in case of crashes to resume from the error point, and even multiple aliases to use the same method (e.g., sp.build_bar_chart / sp.bar_chart / sp.bar / sp.bars).


1000 charts. Measured.

Same code, same random data, same machine. Full HTML output timed.

import seraplot as sp
categories = ["Electronics", "Clothing", "Food", "Books", "Sports", "Toys", "Health", "Auto"]
data = [...]  # 1000 pre-generated lists
for i in range(1000):
    sp.bar(f"Report #{i+1}", categories, data[i]).html

1000 charts in 6 ms — 6 µs/chart

import plotly.graph_objects as go
categories = ["Electronics", "Clothing", "Food", "Books", "Sports", "Toys", "Health", "Auto"]
data = [...]  # same 1000 pre-generated lists
for i in range(1000):
    fig = go.Figure(data=[go.Bar(x=categories, y=data[i])])
    fig.update_layout(title=f"Report #{i+1}", template="plotly_dark")
    fig.to_html(full_html=True, include_plotlyjs="cdn")

1000 charts in 37,023 ms — 6,170× slower

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
categories = ["Electronics", "Clothing", "Food", "Books", "Sports", "Toys", "Health", "Auto"]
data = [...]  # same 1000 pre-generated lists
for i in range(1000):
    fig, ax = plt.subplots(figsize=(9, 5))
    ax.bar(categories, data[i])
    ax.set_title(f"Report #{i+1}")
    fig.savefig(f"chart_{i}.png")
    plt.close()

1000 charts in 60,352 ms — 10,058× slower

ScaleSeraPlotPlotlyMatplotlib
1,000 charts6 ms37 s60 s
10,000 charts~60 ms~6 min~10 min
100,000 charts~600 ms~1 h~1.7 h

Render core speed

Benchmark: Diabetes dataset (n=768, 40 runs). Rust render time — chart object creation, not full HTML serialization.

Pie
7,956×
Bar
6,488×
Lollipop
3,983×
Grouped Bar
3,596×
Candlestick
2,038×
Radar
1,498×
KDE
753×
ChartSeraPlotPlotly figurePlotly → HTMLMatplotlib
Pie4.272533,41615,085
Bar2.865818,16613,596
Grouped Bar5.055817,98117,445
Histogram12.42,49632,76237,973
Scatter17.03,91621,61514,141
Violin16.72,61621,34721,211
Box Plot18.42,32921,79915,590
KDE26.32,98119,80740,108
Radar11.896217,67920,942
Lollipop6.38,38225,0969,072
Candlestick8.81,47817,934N/A
Ridgeline88.8N/AN/AN/A

All times in µs.


Output file size

Plotly embeds its entire JavaScript bundle in every HTML file. SeraPlot only includes the JS needed for that specific chart type.

Pie
19 KB vs 4,733 KB — 246×
Bar
21 KB vs 4,733 KB — 225×
Scatter
39 KB vs 4,740 KB — 121×
Radar
23 KB vs 4,733 KB — 205×

Matplotlib outputs PNG/SVG/PDF (50-500 KB) — not interactive HTML.


What SeraPlot actually is

SeraPlot is not a wrapper around Plotly, Chart.js, or D3.

It is a Rust-native rendering engine that generates minimal HTML + JS per chart. A Pie chart gets Pie JS. A Bar chart gets Bar JS. Nothing else is bundled.

That's why the output is 20 KB instead of 4.7 MB.


One line migration

import seraplot.matplotlib as plt

Everything else stays the same. plt.bar(), plt.scatter(), plt.hist(), plt.show(), plt.savefig() — unchanged.


Deploy from an API

from fastapi import FastAPI
import seraplot as sp
app = FastAPI()
@app.get("/chart")
def revenue_chart():
    return sp.bar("Revenue", labels, values).html
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
import plotly.express as px
app = FastAPI()
@app.get("/chart", response_class=HTMLResponse)
def revenue_chart():
    fig = px.bar(x=labels, y=values, title="Revenue")
    return fig.to_html(full_html=True)
from fastapi import FastAPI
from fastapi.responses import FileResponse
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import tempfile
app = FastAPI()
@app.get("/chart")
def revenue_chart():
    fig, ax = plt.subplots(figsize=(9, 5))
    ax.bar(labels, values)
    ax.set_title("Revenue")
    path = tempfile.mktemp(suffix=".png")
    plt.savefig(path)
    plt.close()
    return FileResponse(path, media_type="image/png")

Plotly returns 4.7 MB per request. Matplotlib requires disk I/O and returns a static PNG. SeraPlot returns 21 KB of interactive HTML directly from RAM.


Everything SeraPlot does

  • 57 chart types — every 2D chart has a 3D WebGL variant
  • Drop-in matplotlib APIimport seraplot.matplotlib as plt
  • Pandas & NumPy native — pass DataFrames directly
  • 7 built-in themes — dark, light, scientific, apple, notion, minimal, neon
  • Global configsp.config() sets font, zoom, crosshair, animation across all charts
  • Zero dependencies — pure Rust renderer
  • 200× smaller files — no bundled JS runtime
  • Multi-language — Python, JavaScript/TypeScript (npm), Rust, R, Scala, C#, C++, Java
  • DBSCAN up to 600× faster than scikit-learn
  • Native Machine learning — some ml methods is include by default in this tool
  • Works everywhere — Python ≥ 3.8, any OS

Seraplot - Bien plus qu'une bibliothèque de graphiques

« Tout tracer. Tout entraîner. Partout déployer. »

SeraPlot est une boîte à outils data complète écrite en Rust. Le même moteur propulse vos visualisations, votre machine learning, et la façon dont vous livrez les résultats à vos collègues.

PilierCe que vous obtenez
Tracer57 types de graphiques — 33 en 2D, 17 en 3D (WebGL), 2 cartes. Thèmes intégrés, palettes, animations, zoom, crosshair, export.
EntraînerML compatible scikit-learn en Rust — DBSCAN, K-Means, RandomForest, GradientBoosting, SVM, PCA, GridSearchCV, train/test split. De 1,3× à 686× plus rapide.
Streamer & passer à l'échelleMises à jour en direct, downsampling pour des millions de points, détection de drift, AutoML, mode diff, grilles de facettes.
DéployerHTML autonome de 21 Ko — pas de CDN, pas de backend, fonctionne hors-ligne, par e-mail, sur S3, dans des PDF, dans Notion, en CI isolée.
IntégrerPython, JavaScript, TypeScript, Rust. Migration directe seraplot.matplotlib as plt. Pandas / NumPy nativement.
CoderExtension VS Code native — aperçu en direct, galerie, studio de thèmes, snippets, détection automatique des labels / values depuis votre code.
Persister & exporterExport HTML, PNG, SVG, PDF, pickle. Rechargement des modèles ML entraînés. Sortie compatible CSP.
Rester accessibleSVG balisé a11y, HTML sémantique, navigation clavier, formatage numérique localisé.

Une seule librairie remplace : matplotlib + plotly + dash + streamlit + seaborn + une partie de scikit-learn — avec un seul pip install et zéro dépendance d'exécution.


Même graphique — trois bibliothèques

import seraplot as sp
sp.bar("Chiffre d'affaires par produit", labels, values).save("chart.html")
import plotly.express as px
fig = px.bar(x=labels, y=values, title="Chiffre d'affaires par produit")
fig.update_layout(template="plotly_white")
fig.write_html("chart.html")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(9, 5))
ax.bar(labels, values, color="#6366f1")
ax.set_title("Chiffre d'affaires par produit")
ax.set_ylabel("Chiffre d'affaires")
plt.tight_layout()
plt.savefig("chart.png")
SeraPlotPlotlyMatplotlib
Lignes de code247
SortieHTMLHTMLPNG
Taille fichier21 Ko4,7 Mo~150 Ko
Interactif
Dépendances06+3+
Migration 1 ligne

Pourquoi Seraplot ?

Comme vous l’aurez compris en arrivant jusqu’ici, Seraplot est un outil qui a pour objectif d’être extrêmement personnalisable, mais aussi beaucoup plus rapide et moins gourmand que ce qui existe déjà, en plus de proposer tout un panel d’aides, comme l’extension Seraplot dans VSCode, qui vous permettra de générer des plots ou des méthodes ML très rapidement et en live, entre chaque sauvegarde de vos scripts.

En plus de cela, Seraplot se voit distribué dans différents langages comme : JS/TS, C (C# & C++), Java, Rust, Python, R & Scala. L’objectif étant vraiment d’être ultra accessible : d’un langage à un autre, les commandes restent les mêmes pour plus de simplicité.

Pour résumer, Seraplot est un outil beaucoup plus pratique de ce qui existe déjà et complétement indépendant, en plus de compilé différente fonctionnalitée. En autre il permet la génération de plots 2D & 3D, mais aussi qui tend à proposer des méthodes liées au ML, que vous pourrez retrouver au cours de votre documentation. D’autres surprises vous attendent, que ce soit la possibilité de choisir différents thèmes, ou bien le système de chunks en cas de crash pour reprendre au point d’erreur, ou encore pour n'en citer que un dernier, le fait d’avoir différents alias pour utiliser une même méthode (ex : sp.build_bar_chart / sp.bar_chart / sp.bar / sp.bars).


1 000 graphiques. Mesurés.

Même code, mêmes données aléatoires, même machine. Sortie HTML complète chronométrée.

import seraplot as sp
categories = ["Électronique", "Vêtements", "Alimentation", "Livres", "Sport", "Jouets", "Santé", "Auto"]
data = [...]
for i in range(1000):
    sp.bar(f"Rapport #{i+1}", categories, data[i]).html

1 000 graphiques en 6 ms — 6 µs/graphique

import plotly.graph_objects as go
categories = ["Électronique", "Vêtements", "Alimentation", "Livres", "Sport", "Jouets", "Santé", "Auto"]
data = [...]
for i in range(1000):
    fig = go.Figure(data=[go.Bar(x=categories, y=data[i])])
    fig.update_layout(title=f"Rapport #{i+1}", template="plotly_dark")
    fig.to_html(full_html=True, include_plotlyjs="cdn")

1 000 graphiques en 37 023 ms — 6 170× plus lent

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
categories = ["Électronique", "Vêtements", "Alimentation", "Livres", "Sport", "Jouets", "Santé", "Auto"]
data = [...]
for i in range(1000):
    fig, ax = plt.subplots(figsize=(9, 5))
    ax.bar(categories, data[i])
    ax.set_title(f"Rapport #{i+1}")
    fig.savefig(f"chart_{i}.png")
    plt.close()

1 000 graphiques en 60 352 ms — 10 058× plus lent

ÉchelleSeraPlotPlotlyMatplotlib
1 000 graphiques6 ms37 s60 s
10 000 graphiques~60 ms~6 min~10 min
100 000 graphiques~600 ms~1 h~1,7 h

Vitesse du moteur de rendu

Benchmark : dataset Diabetes (n=768, 40 itérations). Temps de rendu Rust — création de l'objet graphique, pas la sérialisation HTML complète.

Camembert
7 956×
Barres
6 488×
Sucette
3 983×
Barres groupées
3 596×
Bougie
2 038×
Radar
1 498×
KDE
753×
GraphiqueSeraPlotPlotly figurePlotly → HTMLMatplotlib
Camembert4,272533 41615 085
Barres2,865818 16613 596
Barres groupées5,055817 98117 445
Histogramme12,42 49632 76237 973
Nuage de points17,03 91621 61514 141
Violon16,72 61621 34721 211
Boîte à moustaches18,42 32921 79915 590
KDE26,32 98119 80740 108
Radar11,896217 67920 942
Sucette6,38 38225 0969 072
Bougie8,81 47817 934N/A
Ridgeline88,8N/AN/AN/A

Toutes les valeurs en µs.


Taille des fichiers de sortie

Plotly embarque tout son bundle JavaScript dans chaque fichier HTML. SeraPlot n'inclut que le JS nécessaire au type de graphique spécifique.

Camembert
19 Ko vs 4 733 Ko — 246×
Barres
21 Ko vs 4 733 Ko — 225×
Nuage de points
39 Ko vs 4 740 Ko — 121×
Radar
23 Ko vs 4 733 Ko — 205×

Matplotlib produit du PNG/SVG/PDF (50–500 Ko) — pas du HTML interactif.


Ce qu'est réellement SeraPlot

SeraPlot n'est pas un wrapper autour de Plotly, Chart.js ou D3.

C'est un moteur de rendu natif Rust qui génère du HTML + JS minimal par graphique. chaque chart reçoit soit js dédiée. Rien d'autre n'est embarqué.

C'est pour ça que la sortie fait 20 Ko au lieu de 4,7 Mo.


Migration en une ligne

import seraplot.matplotlib as plt

Tout le reste reste identique. plt.bar(), plt.scatter(), plt.hist(), plt.show(), plt.savefig() — inchangés.


Déployer depuis une API

from fastapi import FastAPI
import seraplot as sp
app = FastAPI()
@app.get("/chart")
def revenue_chart():
    return sp.bar("Chiffre d'affaires", labels, values).html
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
import plotly.express as px
app = FastAPI()
@app.get("/chart", response_class=HTMLResponse)
def revenue_chart():
    fig = px.bar(x=labels, y=values, title="Chiffre d'affaires")
    return fig.to_html(full_html=True)
from fastapi import FastAPI
from fastapi.responses import FileResponse
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import tempfile
app = FastAPI()
@app.get("/chart")
def revenue_chart():
    fig, ax = plt.subplots(figsize=(9, 5))
    ax.bar(labels, values)
    ax.set_title("Chiffre d'affaires")
    path = tempfile.mktemp(suffix=".png")
    plt.savefig(path)
    plt.close()
    return FileResponse(path, media_type="image/png")

Plotly retourne 4,7 Mo par requête. Matplotlib nécessite des I/O disque et retourne un PNG statique. SeraPlot retourne 21 Ko de HTML interactif directement depuis la RAM.


Tout ce que SeraPlot fait

  • 57 types de graphiques — chaque graphique 2D a une variante 3D WebGL
  • API matplotlib drop-inimport seraplot.matplotlib as plt
  • Pandas & NumPy natifs — passez les DataFrames directement
  • 7 thèmes intégrés — dark, light, scientific, apple, notion, minimal, neon
  • Configuration globalesp.config() définit la police, le zoom, le réticule, l'animation pour tous les graphiques
  • Zéro dépendance — moteur de rendu Rust pur
  • Fichiers 200× plus petits — pas de runtime JS embarqué
  • Multi-langage — Python, JavaScript/TypeScript (npm), Rust, R, Scala, C#, C++, Java
  • DBSCAN jusqu'à 600× plus rapide que scikit-learn
  • Machine learning natif — Plusieurs methods ml, sont déjà existante dans le framework
  • Fonctionne partout — Python ≥ 3.8, tout OS

Installation

Requirements

  • Python 3.8+
  • pip 21+

SeraPlot ships as a compiled Rust extension (.pyd / .so) bundled in the wheel. There is no compiler required on the user side — the binary is pre-built for each platform.


Install

Standard Python package installer — works in any environment:

pip install seraplot
pip install seraplot==2.3.61
pip install --upgrade seraplot
💡For project isolation, always install inside a virtual environment: python -m venv .venv && .venv\Scripts\activate
⚡ Recommended — 10–100× faster than pip

uv is a next-generation Python package manager written in Rust — resolves and installs packages in milliseconds.

uv add seraplot
💡Run pip install uv once to install uv, then use uv add in any project.

Install from the conda-forge channel, or declare it in your environment file:

conda install -c conda-forge seraplot

Or add to environment.yml:

dependencies:
  - pip:
    - seraplot

Why the install is this simple

SeraPlot has zero required Python dependencies. The Rust extension is entirely self-contained — the HTML output embeds its own JavaScript inline and does not load anything from a CDN.

🌐 Works offline Charts render in air-gapped environments, emails, PDF exports via browser print — no CDN, no internet.
🔒 No conflicts Zero dependency on numpy, pandas, or scipy — nothing to conflict with your existing stack.
🚀 All platforms Pre-built wheels for Windows, Linux, and macOS. No compiler, no Rust toolchain needed.
🪶 Tiny footprint pip install plotly downloads ~15 MB. pip install seraplot downloads ~2 MB.

Prérequis

  • Python 3.8+
  • pip 21+

SeraPlot se distribue sous forme d'extension Rust compilée (.pyd / .so) incluse dans le wheel. Aucun compilateur n'est requis côté utilisateur — le binaire est pré-compilé pour chaque plateforme.


Installer

Gestionnaire de paquets Python standard — fonctionne dans tous les environnements :

pip install seraplot
pip install seraplot==2.3.61
pip install --upgrade seraplot
💡Pour isoler votre projet, installez toujours dans un environnement virtuel : python -m venv .venv && .venv\Scripts\activate
⚡ Recommandé — 10 à 100× plus rapide que pip

uv est un gestionnaire de paquets Python nouvelle génération écrit en Rust — résout et installe les paquets en quelques millisecondes.

uv add seraplot
💡Exécutez pip install uv une seule fois pour installer uv, puis utilisez uv add dans chaque projet.

Installez depuis le canal conda-forge, ou déclarez-le dans votre fichier d'environnement :

conda install -c conda-forge seraplot

Ou ajoutez dans environment.yml :

dependencies:
  - pip:
    - seraplot

Pourquoi l'installation est aussi simple

SeraPlot n'a aucune dépendance Python requise. L'extension Rust est entièrement autonome — le HTML embarque son propre JavaScript sans rien charger depuis un CDN.

🌐 Fonctionne hors ligne Les graphiques se génèrent en environnement isolé, dans les e-mails, en impression PDF — sans CDN ni internet.
🔒 Zéro conflit Aucune dépendance sur numpy, pandas ou scipy — rien qui puisse entrer en conflit avec votre stack.
🚀 Toutes plateformes Wheels pré-compilés pour Windows, Linux et macOS. Aucun compilateur, aucune toolchain Rust requise.
🪶 Empreinte minimale pip install plotly télécharge ~15 Mo. pip install seraplot télécharge ~2 Mo.

Quick Start

Your first chart in under a minute

SeraPlot is a unified plotting library that ships the same API to nine languages. Pick your stack, install one package, and render an interactive chart with three lines of code.

⚡ Native Rust core 📊 60+ chart types 🌐 9 languages 🪶 Zero JS dependencies
pip install seraplot
npm install seraplot
npm install seraplot
npm install --save-dev @types/seraplot
cargo add seraplot
install.packages("seraplot")
import seraplot as sp

chart = sp.bar( title="Sales by Region", labels=["North", "South", "East", "West"], values=[120, 85, 200, 140], gridlines=True, show_text=True, ) chart.show()

const sp = require("seraplot");

const chart = sp.bar({ title: "Sales by Region", labels: ["North", "South", "East", "West"], values: [120, 85, 200, 140], gridlines: true, show_text: true, }); chart.show();

import * as sp from "seraplot";

const chart = sp.bar({ title: "Sales by Region", labels: ["North", "South", "East", "West"], values: [120, 85, 200, 140], gridlines: true, show_text: true, }); chart.show();

// Cargo.toml: [dependencies] seraplot = "2"
use seraplot::Chart;

fn main() { let chart = Chart::bar() .title("Sales by Region") .labels(["North", "South", "East", "West"]) .values([120.0, 85.0, 200.0, 140.0]) .gridlines(true) .show_text(true) .build(); chart.show(); }

library(seraplot)

chart <- sp_bar( title = "Sales by Region", labels = c("North", "South", "East", "West"), values = c(120, 85, 200, 140), gridlines = TRUE, show_text = TRUE ) chart$show()

💡 Jupyter / notebook: the chart renders inline automatically — no .show() needed.
chart.save("sales.html")    # standalone HTML
chart.save("sales.png")     # raster
chart.save("sales.svg")     # vector
chart.save("sales.html");
chart.save("sales.png");
chart.save("sales.svg");
chart.save("sales.html");
chart.save("sales.png");
chart.save("sales.svg");
#![allow(unused)]
fn main() {
chart.save("sales.html")?;
chart.save("sales.png")?;
chart.save("sales.svg")?;
}
chart$save("sales.html")
chart$save("sales.png")
chart$save("sales.svg")

Where to next?

📊 Chart catalog

Browse bar, line, scatter, heatmaps and 60+ more chart types — each with copy-paste examples in nine languages.

🤖 Machine learning

Train, fit and visualise scikit-learn-style models directly on chart data: regression, clustering, trees, SVM and more.

🎨 Themes & palettes

Customise colors with palettes, themes and per-chart backgrounds.

Votre premier graphique en moins d'une minute

SeraPlot est une bibliothèque graphique unifiée qui expose la même API dans neuf langages. Choisissez votre stack, installez un seul paquet, et générez un graphique interactif en trois lignes.

⚡ Cœur Rust natif 📊 60+ types de graphiques 🌐 9 langages 🪶 Zéro dépendance JS
pip install seraplot
npm install seraplot
npm install seraplot
npm install --save-dev @types/seraplot
cargo add seraplot
install.packages("seraplot")
import seraplot as sp

chart = sp.bar( title="Ventes par région", labels=["Nord", "Sud", "Est", "Ouest"], values=[120, 85, 200, 140], gridlines=True, show_text=True, ) chart.show()

const sp = require("seraplot");

const chart = sp.bar({ title: "Ventes par région", labels: ["Nord", "Sud", "Est", "Ouest"], values: [120, 85, 200, 140], gridlines: true, show_text: true, }); chart.show();

import * as sp from "seraplot";

const chart = sp.bar({ title: "Ventes par région", labels: ["Nord", "Sud", "Est", "Ouest"], values: [120, 85, 200, 140], gridlines: true, show_text: true, }); chart.show();

// Cargo.toml: [dependencies] seraplot = "2"
use seraplot::Chart;

fn main() { let chart = Chart::bar() .title("Ventes par région") .labels(["Nord", "Sud", "Est", "Ouest"]) .values([120.0, 85.0, 200.0, 140.0]) .gridlines(true) .show_text(true) .build(); chart.show(); }

library(seraplot)

chart <- sp_bar( title = "Ventes par région", labels = c("Nord", "Sud", "Est", "Ouest"), values = c(120, 85, 200, 140), gridlines = TRUE, show_text = TRUE ) chart$show()

💡 Jupyter / notebook : le graphique s'affiche automatiquement — pas besoin d'appeler .show().
chart.save("ventes.html")   # HTML autonome
chart.save("ventes.png")    # raster
chart.save("ventes.svg")    # vectoriel
chart.save("ventes.html");
chart.save("ventes.png");
chart.save("ventes.svg");
chart.save("ventes.html");
chart.save("ventes.png");
chart.save("ventes.svg");
#![allow(unused)]
fn main() {
chart.save("ventes.html")?;
chart.save("ventes.png")?;
chart.save("ventes.svg")?;
}
chart$save("ventes.html")
chart$save("ventes.png")
chart$save("ventes.svg")

Et après ?

📊 Catalogue de graphiques

Découvrez barres, lignes, nuages de points, heatmaps et 60+ autres types — chacun avec des exemples copier-coller dans neuf langages.

🤖 Machine learning

Entraînez et visualisez des modèles façon scikit-learn directement sur vos données : régression, clustering, arbres, SVM…

🎨 Thèmes & palettes

Personnalisez les couleurs avec palettes, thèmes et arrière-plans par graphique.

⚡ Streaming & big data

Affichez des millions de points grâce au sous-échantillonnage, au streaming live et aux mises à jour diff.

Chart methods

Chart methods & global config

Every Chart object returned by SeraPlot supports the same fluent API. Set defaults once with sp.config() and tweak per chart with chainable methods. All methods return a new Chart, so chaining is always safe.

Fluent APIGlobal + per-chart override60+ chart typesPlotly-compatible value labels

Set defaults once. Every chart created afterwards inherits this configuration automatically.

ParameterTypeDefaultEffect
fontstrsystemFont family for every text element
font_sizeint12Base font size in px
title_sizeint16Title font size in px
border_radiusint0Container border radius (px)
opacityfloat1.0Element opacity 0.0–1.0
responsiveboolFalseAuto-resize to container width
animationboolFalseFade-in animation on chart load
animation_durationint300Animation duration in ms
crosshairboolFalseCrosshair lines follow mouse hover
zoomboolFalseMouse wheel zoom + pan (double-click resets)
tooltipstrTooltip mode
localestrNumber formatting locale
thousands_sepstrThousands separator character
marginint0Container padding (px)
export_buttonboolFalseShow download button on each chart
palettelist[int]Color palette as hex ints (e.g. [0x6366F1,0xFB7185])
backgroundstrBackground color (any CSS color)
gridlinesboolFalseShow grid lines in chart
text_autobool / strFalseDisplay values on bars/markers (True raw, or d3 format like ".2s")
text_positionstr"auto""auto" / "inside" / "outside"
text_angleint0Value label rotation (deg)
text_font_sizeint12Max font size for value labels (px)
text_font_colorstrValue label color
uniform_text_min_sizeint0Minimum px before label is hidden
uniform_text_modestr"hide""hide" small labels or "show" overflow
bar_corner_radiusint / str0Bar corner radius in px or "20%" of bar width
sp.config(**kwargs)global
Apply persistent defaults to all subsequent charts.
import seraplot as sp

sp.config( font="Inter", font_size=12, title_size=16, crosshair=True, zoom=True, animation=True, palette=[0x6366F1, 0xFB7185, 0x10B981], background="#fafafa", border_radius=8, margin=16, ) chart = sp.bar("Sales", ["Q1","Q2","Q3"], [100,150,120])

sp.reset_config()global
Clear every global setting back to factory defaults.
sp.reset_config()
chart = sp.bar("Clean", labels, values)

Curated presets that combine palette, background and gridlines.

ThemeMood
"dark"High-contrast dark dashboard
"light"Soft pastel light backdrop
"scientific"Publication-style monochrome
"apple"Glassy iOS-inspired palette
"notion"Calm Notion-style neutrals
"minimal"Bare lines, no chrome
"neon"Vibrant cyberpunk neons
sp.theme(name)global
Apply a preset theme. Combine with sp.config() overrides.
sp.theme("dark")
chart = sp.bar("Modern", labels, values)
sp.themes() -> list[str]global
List every available theme name.
available = sp.themes()
print(available)
sp.reset_theme()global
Reset back to no theme (default palette, no background, no gridlines).
sp.reset_theme()
.set_bg(color=None) -> Chartchainable
Set the HTML wrapper background. Accepts any CSS color or None for transparent.
chart = sp.line("Trend", x, y).set_bg("#0f172a")
chart = sp.pie("Share", labels, values).set_bg(None)
.set_frame(color=None) -> Chartchainable
Set the SVG canvas background, independent from the HTML wrapper.
chart = sp.bar("Title", labels, values).set_frame("transparent")
sp.set_global_background(color)global
Apply a background to every chart created afterwards. Useful for notebooks.
sp.set_global_background("#0f172a")
chart1 = sp.bar(...)
chart2 = sp.scatter(...)
sp.reset_global_background()
.show_grid() -> Chartchainable
Force gridlines on (overrides config).
chart = sp.bar("Data", labels, values).show_grid()
.hide_grid() -> Chartchainable
Force gridlines off.
chart = sp.bar("Data", labels, values, gridlines=True).hide_grid()
.no_x_axis() -> Chartchainable
Drop X-axis line, ticks and labels.
chart = sp.bar("Y only", labels, values).no_x_axis()
.no_y_axis() -> Chartchainable
Drop Y-axis line, ticks and labels.
chart = sp.bar("X only", labels, values).no_y_axis()
.no_axes() -> Chartchainable
Drop both axes at once.
chart = sp.scatter("Clean", x, y).no_axes()
.no_title() -> Chartchainable
Hide the chart title.
chart = sp.pie("Internal", labels, values).no_title()
.no_legend() -> Chartchainable
Hide the legend (multi-series charts).
chart = sp.grouped_bar("Q1", cats, series).no_legend()
.title_size(px: int) -> Chartchainable
Override title font size for this chart.
chart = sp.bar("Big", labels, values).title_size(24)
.font(name: str) -> Chartchainable
Override the font family for this chart.
chart = sp.bar("Roboto", labels, values).font("Roboto")
.set_font_size(px: int) -> Chartchainable
Override base text size for all axis/legend labels.
chart = sp.radar("Skills", labels, values).set_font_size(11)
.text_font(family=None, size=None, color=None) -> Chartchainable
Style the value labels (text_auto family).
chart = sp.bar("Styled", labels, values).text_font(family="Courier", size=11, color="#333")
Tip: works on every chart that emits data-v attributes — bars, lollipops, scatter, pie, treemap, line markers… Format strings follow d3 / Plotly conventions: ".2s", ".0f", ".1%".
.text_auto(format=True, position=None, angle=None, font_size=None, color=None) -> Chartchainable
Show value labels on every data point. format=True uses raw values; pass a d3 format string for fancy formatting.
chart = sp.bar("Raw", labels, values).text_auto(True)
chart = sp.pie("Pct", labels, values).text_auto(".1%", position="outside")
chart = sp.bar("SI", labels, values).text_auto(".2s", angle=45, font_size=13)
.text_position(position: str) -> Chartchainable
Override label placement: "auto", "inside", "outside".
chart = sp.bar("Out", labels, values).text_position("outside")
.text_angle(degrees: int) -> Chartchainable
Rotate value labels by N degrees.
chart = sp.bar("Rot", labels, values).text_angle(90)
.uniform_text(min_size=8, mode="hide") -> Chartchainable
Force consistent label sizing. mode="hide" drops labels smaller than min_size; "show" allows overflow.
chart = sp.bar("Uniform", labels, values).uniform_text(min_size=10, mode="hide")
.corner_radius_bars(radius) -> Chartchainable
Round bar corners. Accepts an integer (pixels) or a string like "20%" of the bar width.
chart = sp.bar("Modern", labels, values).corner_radius_bars(8)
chart = sp.bar("Pct", labels, values).corner_radius_bars("15%")
.animate(duration=300) -> Chartchainable
Fade-in animation. Pass duration in ms.
chart = sp.bar("Fade", labels, values).animate(500)
.crosshair() -> Chartchainable
Crosshair lines follow the mouse.
chart = sp.scatter("XY", x, y).crosshair()
.zoom() -> Chartchainable
Mouse-wheel zoom and pan; double-click resets.
chart = sp.line("Big", x, y).zoom()
.no_hover() -> Chartchainable
Disable all hover effects and tooltips.
chart = sp.bar("Static", labels, values).no_hover()
.responsive() -> Chartchainable
Auto-resize to the parent container width.
chart = sp.bar("Fluid", labels, values).responsive()
.border_radius(px: int) -> Chartchainable
Set the container border radius.
chart = sp.bar("Round", labels, values).border_radius(12)
.set_margin(px: int) -> Chartchainable
Set the container padding.
chart = sp.scatter("Pad", x, y).set_margin(20)
.set_opacity(value: float) -> Chartchainable
Set element opacity (0.0–1.0).
chart = sp.bar("Faded", labels, values).set_opacity(0.7)
.scale(factor: float) -> Chartchainable
Scale chart by multiplier (1.0 = normal).
chart = sp.pie("Big", labels, values).scale(1.5)
.save(path: str)export
Write chart HTML to disk.
chart.save("chart.html")
.show()export
Display chart in Jupyter via IPython.display.
sp.scatter("Data", x, y).show()
.to_svg() -> strexport
Return the inner <svg> element as a string.
svg = chart.to_svg()
.export_svg(path: str)export
Save the SVG portion to disk.
chart.export_svg("chart.svg")
.export_png(path: str, scale=2.0)export
Export PNG (requires cairosvg).
chart.export_png("chart.png", scale=1.5)
.export_button() -> Chartchainable
Add a download button on the chart.
chart = sp.pie("Share", labels, values).export_button()
.inject_css(css: str) -> Chartchainable
Inject extra CSS into the chart's <head>.
chart = sp.bar("X", labels, values).inject_css(".sp-ttl{color:#22c55e}")
.inject_js(js: str) -> Chartchainable
Inject extra JavaScript at the end of the body.
chart = sp.bar("X", labels, values).inject_js("console.log('loaded')")
.show_labels(position="bottom", labels=None, colors=None) -> Chartchainable
Render a clickable text label overlay (alternative legend).
chart = sp.bar("Q", labels, values).show_labels(
    "top", labels=["Series A", "Series B"], colors=["#6366F1", "#FB7185"]
)
.a11y(title="", desc="") -> Chartchainable
Inject ARIA title and desc for screen readers.
chart = sp.bar("Sales", labels, values).a11y(title="Q1–Q4 revenue", desc="Bar chart showing quarterly revenue trends")
.csp_safe() -> Chartchainable
Move inline scripts to data-* attributes for strict Content-Security-Policy environments.
chart = sp.bar("CSP", labels, values).csp_safe()
.downsample(n=2000, method="lttb") -> Chartchainable
Reduce data points using LTTB (Largest-Triangle-Three-Buckets) for very large series.
chart = sp.line("Big", xs, ys).downsample(n=1000)
.diff(other: Chart) -> strchainable
Compare two charts and return a JSON diff describing structural and stylistic differences.
a = sp.bar("v1", labels, vals1)
b = sp.bar("v2", labels, vals2)
print(a.diff(b))
.doc() -> strproperty
Return the full inline documentation for the chart type.
print(chart.doc())
.html # propertyproperty
Read the full HTML payload as a string.
src = chart.html
len(chart) -> intproperty
Returns the size of the HTML payload in bytes.
print(len(chart))
bool(chart) -> boolproperty
True when the chart has rendered output.
if chart:
    chart.show()
16

Annotations (cross-chart)

SVG overlays inherited by every plot

annotations=[...] (kwarg)newglobal
Pass a list of annotation dicts to any chart builder. Coordinates default to fractional canvas space (0.0 - 1.0); set "frac": false to use raw pixels. Supported kind values: "hline", "vline", "line", "arrow", "rect", "text".
chart = sp.build_line_chart(
    "Sales", labels=months, values=sales,
    annotations=[
        {"kind":"hline", "y":0.5, "color":"#22c55e", "dash":"6 4", "text":"Target"},
        {"kind":"vline", "x":0.62, "color":"#f59e0b", "text":"Launch"},
        {"kind":"rect",  "x":0.05, "y":0.65, "x2":0.40, "y2":0.92,
                         "color":"#6366f1", "fill":"#6366f1", "opacity":0.10},
        {"kind":"arrow", "x":0.45, "y":0.30, "x2":0.85, "y2":0.18, "color":"#ef4444"},
        {"kind":"text",  "x":0.46, "y":0.28, "text":"Outlier", "color":"#ef4444"},
    ],
)
Annotation fields
Every annotation accepts the same shape:
FieldTypeDefaultDescription
kindstrrequiredhline / vline / line / arrow / rect / text
x, yfloat0.5Anchor point (frac of canvas if frac=True, pixels otherwise)
x2, y2float1.0End point for line / arrow / rect
colorstr"#ef4444"Stroke / text color (CSS)
fillstr"none"Fill color (rect only)
stroke_widthfloat1.5Stroke width
dashstr""SVG dash array, e.g. "6 4"
opacityfloat1.00.0 - 1.0
textstrNoneOptional label rendered next to the primitive
font_sizefloat11.0Label font size
fracbooltrueCoordinate space: fractional (0-1) or pixel
Tip: Annotations apply uniformly to every 2D and 3D chart through the apply_annotations() hook - no per-chart wiring required.
17

Composers (Grid + Slideshow)

Group charts into stories

sp.grid(charts, cols=3, gap=16, bg_color="#0a0f1c", title="", cell_height=None) -> Chartnew
Compose any number of pre-built charts into a responsive CSS-grid layout, each chart hosted in its own iframe. sp.build_grid is an identical alias. cell_height defaults to the chart's own height attribute.
bar  = sp.build_bar_chart("Q-Sales", labels=["Q1","Q2","Q3","Q4"], values=[120,180,150,210])
line = sp.build_line_chart("Trend", labels=months, values=sales)
pie  = sp.build_pie_chart("Mix", labels=["A","B","C"], values=[40,35,25])

grid = sp.grid([bar, line, pie], cols=3, gap=14, title="Dashboard") grid.show()

sp.build_slideshow(charts, interval_ms=2500, title='', width=900, height=520) -> Chartnew
Build a navigable HTML carousel with previous / next buttons and an auto-advance progress bar - perfect for telling a story without a slide deck.
slides = [sp.build_bar_chart(f"Slide {i+1}", labels=["A","B"], values=[i, i+1]) for i in range(4)]
show = sp.build_slideshow(slides, interval_ms=2200, title="Quarterly Story")
show.show()

Méthodes & configuration globale

Tout objet Chart renvoyé par SeraPlot expose la même API fluide. Définis les valeurs par défaut une fois avec sp.config(), ajuste chart par chart avec des méthodes chaînées. Toutes les méthodes retournent un nouveau Chart : le chaînage est toujours sûr.

API fluideGlobal + override par chart60+ types de graphiquesÉtiquettes Plotly

Définis les défauts une fois. Tous les graphiques créés ensuite héritent automatiquement de cette configuration.

ParamètreTypeDéfautEffet
fontstrsystemFont family for every text element
font_sizeint12Base font size in px
title_sizeint16Title font size in px
border_radiusint0Container border radius (px)
opacityfloat1.0Element opacity 0.0–1.0
responsiveboolFalseAuto-resize to container width
animationboolFalseFade-in animation on chart load
animation_durationint300Animation duration in ms
crosshairboolFalseCrosshair lines follow mouse hover
zoomboolFalseMouse wheel zoom + pan (double-click resets)
tooltipstrTooltip mode
localestrNumber formatting locale
thousands_sepstrThousands separator character
marginint0Container padding (px)
export_buttonboolFalseShow download button on each chart
palettelist[int]Color palette as hex ints (e.g. [0x6366F1,0xFB7185])
backgroundstrBackground color (any CSS color)
gridlinesboolFalseShow grid lines in chart
text_autobool / strFalseDisplay values on bars/markers (True raw, or d3 format like ".2s")
text_positionstr"auto""auto" / "inside" / "outside"
text_angleint0Value label rotation (deg)
text_font_sizeint12Max font size for value labels (px)
text_font_colorstrValue label color
uniform_text_min_sizeint0Minimum px before label is hidden
uniform_text_modestr"hide""hide" small labels or "show" overflow
bar_corner_radiusint / str0Bar corner radius in px or "20%" of bar width
sp.config(**kwargs)global
Applique des défauts persistants à tous les charts suivants.
import seraplot as sp

sp.config( font="Inter", font_size=12, title_size=16, crosshair=True, zoom=True, animation=True, palette=[0x6366F1, 0xFB7185, 0x10B981], background="#fafafa", border_radius=8, margin=16, ) chart = sp.bar("Sales", ["Q1","Q2","Q3"], [100,150,120])

sp.reset_config()global
Remet chaque paramètre global aux valeurs d'usine.
sp.reset_config()
chart = sp.bar("Clean", labels, values)

Préréglages combinant palette, fond et grille.

ThemeMood
"dark"Tableau de bord sombre haut contraste
"light"Fond clair pastel doux
"scientific"Style publication monochrome
"apple"Palette inspirée iOS, glassy
"notion"Neutres calmes type Notion
"minimal"Lignes pures, sans décoration
"neon"Néons cyberpunk vibrants
sp.theme(name)global
Applique un thème prédéfini. Cumulable avec sp.config().
sp.theme("dark")
chart = sp.bar("Modern", labels, values)
sp.themes() -> list[str]global
Liste tous les thèmes disponibles.
available = sp.themes()
print(available)
sp.reset_theme()global
Revient à aucun thème (palette par défaut, sans fond, sans grille).
sp.reset_theme()
.set_bg(color=None) -> Chartchainable
Définit le fond du conteneur HTML. Toute couleur CSS ou None pour transparent.
chart = sp.line("Trend", x, y).set_bg("#0f172a")
chart = sp.pie("Share", labels, values).set_bg(None)
.set_frame(color=None) -> Chartchainable
Définit le fond du canvas SVG, indépendant du conteneur HTML.
chart = sp.bar("Title", labels, values).set_frame("transparent")
sp.set_global_background(color)global
Applique un fond à tous les charts créés ensuite. Utile pour les notebooks.
sp.set_global_background("#0f172a")
chart1 = sp.bar(...)
chart2 = sp.scatter(...)
sp.reset_global_background()
.show_grid() -> Chartchainable
Force la grille active (override config).
chart = sp.bar("Data", labels, values).show_grid()
.hide_grid() -> Chartchainable
Force la grille à OFF.
chart = sp.bar("Data", labels, values, gridlines=True).hide_grid()
.no_x_axis() -> Chartchainable
Supprime l'axe X (ligne, ticks, labels).
chart = sp.bar("Y only", labels, values).no_x_axis()
.no_y_axis() -> Chartchainable
Supprime l'axe Y (ligne, ticks, labels).
chart = sp.bar("X only", labels, values).no_y_axis()
.no_axes() -> Chartchainable
Supprime les deux axes en même temps.
chart = sp.scatter("Clean", x, y).no_axes()
.no_title() -> Chartchainable
Masque le titre.
chart = sp.pie("Internal", labels, values).no_title()
.no_legend() -> Chartchainable
Masque la légende (charts multi-séries).
chart = sp.grouped_bar("Q1", cats, series).no_legend()
.title_size(px: int) -> Chartchainable
Override la taille du titre pour ce chart.
chart = sp.bar("Big", labels, values).title_size(24)
.font(name: str) -> Chartchainable
Override la police pour ce chart.
chart = sp.bar("Roboto", labels, values).font("Roboto")
.set_font_size(px: int) -> Chartchainable
Override la taille de base de tous les labels.
chart = sp.radar("Skills", labels, values).set_font_size(11)
.text_font(family=None, size=None, color=None) -> Chartchainable
Style les étiquettes de valeur (famille text_auto).
chart = sp.bar("Styled", labels, values).text_font(family="Courier", size=11, color="#333")
Astuce : fonctionne sur tous les charts qui exposent data-v — barres, lollipops, scatter, pie, treemap, marqueurs de ligne… Les formats suivent d3 / Plotly : ".2s", ".0f", ".1%".
.text_auto(format=True, position=None, angle=None, font_size=None, color=None) -> Chartchainable
Affiche les valeurs sur chaque point. format=True = brut ; passe un format d3 pour personnaliser.
chart = sp.bar("Raw", labels, values).text_auto(True)
chart = sp.pie("Pct", labels, values).text_auto(".1%", position="outside")
chart = sp.bar("SI", labels, values).text_auto(".2s", angle=45, font_size=13)
.text_position(position: str) -> Chartchainable
Override la position : "auto", "inside", "outside".
chart = sp.bar("Out", labels, values).text_position("outside")
.text_angle(degrees: int) -> Chartchainable
Tourne les étiquettes de N degrés.
chart = sp.bar("Rot", labels, values).text_angle(90)
.uniform_text(min_size=8, mode="hide") -> Chartchainable
Force une taille uniforme. mode="hide" masque les labels < min_size ; "show" autorise l'overflow.
chart = sp.bar("Uniform", labels, values).uniform_text(min_size=10, mode="hide")
.corner_radius_bars(radius) -> Chartchainable
Arrondit les coins. Entier (pixels) ou chaîne type "20%" de la largeur de barre.
chart = sp.bar("Modern", labels, values).corner_radius_bars(8)
chart = sp.bar("Pct", labels, values).corner_radius_bars("15%")
.animate(duration=300) -> Chartchainable
Animation fade-in. Durée en ms.
chart = sp.bar("Fade", labels, values).animate(500)
.crosshair() -> Chartchainable
Lignes crosshair qui suivent la souris.
chart = sp.scatter("XY", x, y).crosshair()
.zoom() -> Chartchainable
Zoom molette + pan ; double-clic = reset.
chart = sp.line("Big", x, y).zoom()
.no_hover() -> Chartchainable
Désactive les effets hover et les tooltips.
chart = sp.bar("Static", labels, values).no_hover()
.responsive() -> Chartchainable
Redimensionnement auto sur la largeur parent.
chart = sp.bar("Fluid", labels, values).responsive()
.border_radius(px: int) -> Chartchainable
Définit le rayon des coins du conteneur.
chart = sp.bar("Round", labels, values).border_radius(12)
.set_margin(px: int) -> Chartchainable
Définit le padding du conteneur.
chart = sp.scatter("Pad", x, y).set_margin(20)
.set_opacity(value: float) -> Chartchainable
Opacité des éléments (0.0–1.0).
chart = sp.bar("Faded", labels, values).set_opacity(0.7)
.scale(factor: float) -> Chartchainable
Mise à l'échelle (1.0 = normal).
chart = sp.pie("Big", labels, values).scale(1.5)
.save(path: str)export
Écrit le HTML du chart sur disque.
chart.save("chart.html")
.show()export
Affiche dans Jupyter via IPython.display.
sp.scatter("Data", x, y).show()
.to_svg() -> strexport
Renvoie l'élément <svg> sous forme de chaîne.
svg = chart.to_svg()
.export_svg(path: str)export
Sauve la partie SVG sur disque.
chart.export_svg("chart.svg")
.export_png(path: str, scale=2.0)export
Export PNG (nécessite cairosvg).
chart.export_png("chart.png", scale=1.5)
.export_button() -> Chartchainable
Ajoute un bouton de téléchargement.
chart = sp.pie("Share", labels, values).export_button()
.inject_css(css: str) -> Chartchainable
Injecte du CSS dans le <head> du chart.
chart = sp.bar("X", labels, values).inject_css(".sp-ttl{color:#22c55e}")
.inject_js(js: str) -> Chartchainable
Injecte du JavaScript en fin de body.
chart = sp.bar("X", labels, values).inject_js("console.log('loaded')")
.show_labels(position="bottom", labels=None, colors=None) -> Chartchainable
Ajoute des étiquettes textuelles cliquables (légende alternative).
chart = sp.bar("Q", labels, values).show_labels(
    "top", labels=["Series A", "Series B"], colors=["#6366F1", "#FB7185"]
)
.a11y(title="", desc="") -> Chartchainable
Ajoute title et desc ARIA pour les lecteurs d'écran.
chart = sp.bar("Sales", labels, values).a11y(title="Q1–Q4 revenue", desc="Bar chart showing quarterly revenue trends")
.csp_safe() -> Chartchainable
Déplace les scripts inline en attributs data-* pour les environnements CSP strict.
chart = sp.bar("CSP", labels, values).csp_safe()
.downsample(n=2000, method="lttb") -> Chartchainable
Réduit le nombre de points avec LTTB (Largest-Triangle-Three-Buckets) pour les grosses séries.
chart = sp.line("Big", xs, ys).downsample(n=1000)
.diff(other: Chart) -> strchainable
Compare deux charts et renvoie un diff JSON décrivant les différences.
a = sp.bar("v1", labels, vals1)
b = sp.bar("v2", labels, vals2)
print(a.diff(b))
.doc() -> strproperty
Renvoie la documentation inline complète du type de chart.
print(chart.doc())
.html # propertyproperty
Lit le HTML complet sous forme de chaîne.
src = chart.html
len(chart) -> intproperty
Renvoie la taille du HTML en octets.
print(len(chart))
bool(chart) -> boolproperty
True si le chart a un rendu.
if chart:
    chart.show()
16

Annotations (transversales)

Surcouches SVG heritees par tous les plots

annotations=[...] (kwarg)nouveauglobal
Passe une liste de dictionnaires d annotations a n importe quel builder. Coordonnees fractionnaires par defaut (0.0 - 1.0) ; mets "frac": false pour utiliser des pixels. Valeurs supportees pour kind : "hline", "vline", "line", "arrow", "rect", "text".
chart = sp.build_line_chart(
    "Ventes", labels=mois, values=ventes,
    annotations=[
        {"kind":"hline", "y":0.5, "color":"#22c55e", "dash":"6 4", "text":"Cible"},
        {"kind":"vline", "x":0.62, "color":"#f59e0b", "text":"Lancement"},
        {"kind":"rect",  "x":0.05, "y":0.65, "x2":0.40, "y2":0.92,
                         "color":"#6366f1", "fill":"#6366f1", "opacity":0.10},
        {"kind":"arrow", "x":0.45, "y":0.30, "x2":0.85, "y2":0.18, "color":"#ef4444"},
        {"kind":"text",  "x":0.46, "y":0.28, "text":"Outlier", "color":"#ef4444"},
    ],
)
Champs d annotation
Toutes les annotations partagent la meme structure :
ChampTypeDefautDescription
kindstrrequishline / vline / line / arrow / rect / text
x, yfloat0.5Point d ancrage (frac canvas si frac=True, pixels sinon)
x2, y2float1.0Point final pour line / arrow / rect
colorstr"#ef4444"Couleur de trait / texte (CSS)
fillstr"none"Couleur de remplissage (rect uniquement)
stroke_widthfloat1.5Epaisseur du trait
dashstr""SVG dash array, ex. "6 4"
opacityfloat1.00.0 - 1.0
textstrNoneEtiquette optionnelle a cote du primitif
font_sizefloat11.0Taille de la police de l etiquette
fracbooltrueEspace de coordonnees : fractionnaire (0-1) ou pixel
Astuce : les annotations s appliquent uniformement a tous les charts 2D et 3D via le hook apply_annotations() - aucun branchement par chart requis.
17

Composers (Grid + Slideshow)

Regroupe des charts en histoires

sp.grid(charts, cols=3, gap=16, bg_color="#0a0f1c", title="", cell_height=None) -> Chartnouveau
Empile N charts deja construits dans une grille CSS responsive, chaque chart isole dans son iframe. sp.build_grid est un alias identique. cell_height utilise par defaut la hauteur detectee dans le chart.
bar  = sp.build_bar_chart("Ventes-Q", labels=["Q1","Q2","Q3","Q4"], values=[120,180,150,210])
line = sp.build_line_chart("Tendance", labels=mois, values=ventes)
pie  = sp.build_pie_chart("Mix", labels=["A","B","C"], values=[40,35,25])

grid = sp.grid([bar, line, pie], cols=3, gap=14, title="Tableau de bord") grid.show()

sp.build_slideshow(charts, interval_ms=2500, title='', width=900, height=520) -> Chartnouveau
Construit un carrousel HTML navigable avec boutons precedent/suivant et barre de progression - parfait pour raconter une histoire sans presentation externe.
slides = [sp.build_bar_chart(f"Slide {i+1}", labels=["A","B"], values=[i, i+1]) for i in range(4)]
show = sp.build_slideshow(slides, interval_ms=2200, title="Histoire trimestrielle")
show.show()

2D Charts

SeraPlot provides 33 two-dimensional chart types, from basic bar and line charts to specialized plots like ridgeline, dumbbell, and slideshow.

ChartFunction
Bar Chartbar()
Horizontal Barhbar()
Line Chartline()
Scatter Chartscatter()
Histogramhistogram()
Histogram Overlayhistogram_overlay()
Grouped Bargrouped_bar()
Stacked Barstacked_bar()
Heatmapheatmap()
Pie Chartpie()
Donut Chartdonut()
Box Plotboxplot()
Violin Chartviolin()
Slope Chartslope()
Sunburstsunburst()
Funnelfunnel()
Treemaptreemap()
Multi-line Chartmultiline()
Area Chartarea()
Waterfallwaterfall()
Bullet Chartbullet()
Word Cloudwordcloud()
Candlestickcandlestick()
Dumbbelldumbbell()
Bubblebubble()
Gaugegauge()
Parallel Coordinatesparallel()
Lollipoplollipop()
KDEkde()
Ridgelineridgeline()
Radarradar()
Grid Layoutgrid()
Slideshowslideshow()

SeraPlot propose 33 types de graphiques 2D, des barres et courbes basiques aux graphiques spécialisés (ridgeline, haltère, slideshow…).

GraphiqueFonction
Graphique en barresbar()
Barres horizontaleshbar()
Courbeline()
Nuage de pointsscatter()
Histogrammehistogram()
Histogramme superposéhistogram_overlay()
Barres groupéesgrouped_bar()
Barres empiléesstacked_bar()
Heatmapheatmap()
Camembertpie()
Anneaudonut()
Boîte à moustachesboxplot()
Violonviolin()
Penteslope()
Sunburstsunburst()
Entonnoirfunnel()
Treemaptreemap()
Multi-courbesmultiline()
Airesarea()
Cascadewaterfall()
Bulletbullet()
Nuage de motswordcloud()
Bougiecandlestick()
Haltèredumbbell()
Bullesbubble()
Jaugegauge()
Coordonnées parallèlesparallel()
Sucettelollipop()
KDEkde()
Ridgelineridgeline()
Radarradar()
Grillegrid()
Diaporamaslideshow()

Bar Charts

Signature

sp.bar(title, labels=None, values=None, *, variant="basic", series=None, **kwargs) -> Chart

Description

sp.bar() is the unified entry point for the entire bar-chart family. The variant keyword selects the rendering strategy — all other arguments remain consistent across variants.

Parameters

ParameterUsed by variants
bar_gapgrouped_stacked, relative
bargroup_gapgrouped_stacked
category_labelsgrouped, grouped_stacked, marimekko, multicategory, relative
color_groupsbasic
color_hexbasic, deluxe, pictogram, prism
corner_radiusgrouped_stacked, relative
gridlinesbasic, deluxe, grouped, grouped_stacked, marimekko, multicategory, prism, relative
heightall
hoverbasic, deluxe, grouped, prism
icon_sizepictogram
labelsbasic, deluxe, pictogram, prism
legend_positiongrouped, grouped_stacked, marimekko, multicategory, relative
max_icons_per_columnpictogram
offset_groupsgrouped_stacked
orientationgrouped
paletteall
seriesgrouped, grouped_stacked, marimekko, multicategory, relative
show_textbasic, deluxe, grouped, marimekko, prism
sort_orderbasic, grouped
super_categoriesmulticategory
titleall
unit_descriptionpictogram
units_per_iconpictogram
valuesbasic, deluxe, multicategory, pictogram, prism
widthall
widthsmarimekko
x_labelbasic, grouped, grouped_stacked, marimekko, multicategory, relative
y_labelbasic, grouped, grouped_stacked, marimekko, multicategory, relative

Returns

Chart — object with .html property and .show() method.



Line Charts

Signature

sp.line(title, labels=None, values=None, *, variant="basic", series=None, **kwargs) -> Chart

Description

sp.line() is the unified entry point for the entire line-chart family. The variant keyword selects the rendering strategy — every other argument is shared across variants.

Parameters

ParameterUsed by variants
color_hexbasic, connected_scatter, dashed, filled, gapped, sparkline, spline, stepped
dash_patterndashed
fill_opacityfilled
gap_thresholdgapped
gridlinesbasic, connected_scatter, dashed, filled, gapped, multi, neon, spline, stepped
heightbasic, connected_scatter, dashed, filled, gapped, multi, neon, spline, stepped
hoverbasic, multi
labelsbasic, connected_scatter, dashed, filled, gapped, neon, spline, stepped
legend_positionconnected_scatter, dashed, filled, gapped, multi, neon
marker_sizeconnected_scatter, gapped, spline, stepped
paletteconnected_scatter, dashed, filled, gapped, multi, neon, sparkline
seriesconnected_scatter, dashed, filled, gapped, multi, neon, sparkline
show_pointsbasic, gapped, multi, neon, spline, stepped
sort_orderbasic, multi
spark_cell_hsparkline
spark_cell_wsparkline
spark_colssparkline
spline_tensionspline
stack_fillfilled
step_shapestepped
stroke_widthconnected_scatter, dashed, filled, gapped, sparkline, spline, stepped
titleall
valuesbasic, connected_scatter, dashed, filled, gapped, neon, sparkline, spline, stepped
widthbasic, connected_scatter, dashed, filled, gapped, multi, neon, spline, stepped
x_labelbasic, connected_scatter, dashed, filled, gapped, multi, neon, spline, stepped
x_labelsconnected_scatter, dashed, filled, gapped, multi, neon
y_labelbasic, connected_scatter, dashed, filled, gapped, multi, neon, spline, stepped

Returns

Chart — object with .html property and .show() method.


Scatter Charts

Signature

sp.scatter(title, x_values, y_values, *, variant="basic", categories=None, labels=None, color_values=None, **kwargs) -> Chart

Description

sp.scatter() is the unified entry point for the entire scatter family. The variant keyword selects the rendering strategy — every other argument keeps the same name across variants. Scatter plots are the canonical way to display the joint distribution of two numeric variables; SeraPlot adds optional grouping, continuous color, distinct marker shapes, on-point labels and OLS regression — all in pure Rust SVG, thousands of times faster than Plotly.

Parameters

ParameterUsed by variants
categoriescategorical, labeled, symbols
color_hexbasic, labeled, regression, symbols
color_highgradient, regression
color_lowgradient
color_valuesgalaxy, gradient, nova
gridlinesall
hoverall
labelsbasic, deluxe, galaxy, gradient, labeled, nova, regression
palettecategorical, labeled, symbols
point_sizeall
regression_typeregression
stroke_widthbasic, categorical, gradient, labeled, regression, symbols
symbolbasic, categorical, gradient, labeled, regression
symbolssymbols
titleall
widthcategorical, gradient, symbols
x_labelall
x_valuesall
y_labelall
y_valuesall

Returns

Chart — object with .html property and .show() method.


Signature

sp.scatter(title, x_values, y_values, *, variant="basic", categories=None, labels=None, color_values=None, **kwargs) -> Chart

Description

sp.scatter() est le point d'entrée unifié de toute la famille scatter. Le mot-clé variant sélectionne la stratégie de rendu — tous les autres arguments gardent le même nom d'une variante à l'autre. Les nuages de points sont la façon canonique d'afficher la distribution conjointe de deux variables numériques ; SeraPlot ajoute groupement optionnel, couleur continue, formes de marqueurs distinctes, étiquettes sur les points et régression OLS — le tout en SVG Rust pur, des milliers de fois plus rapide que Plotly.

Paramètres

ParamètreUtilisé par variantes
categoriescategorical, labeled, symbols
color_hexbasic, labeled, regression, symbols
color_highgradient, regression
color_lowgradient
color_valuesgalaxy, gradient, nova
gridlinestoutes
hovertoutes
labelsbasic, deluxe, galaxy, gradient, labeled, nova, regression
palettecategorical, labeled, symbols
point_sizetoutes
regression_typeregression
stroke_widthbasic, categorical, gradient, labeled, regression, symbols
symbolbasic, categorical, gradient, labeled, regression
symbolssymbols
titletoutes
widthcategorical, gradient, symbols
x_labeltoutes
x_valuestoutes
y_labeltoutes
y_valuestoutes

Retour

Chart — objet exposant .html et .show().


Bubble Charts

Signature

sp.bubble(title, x_values, y_values, sizes, *, variant="basic", categories=None, labels=None, color_values=None, **kwargs) -> Chart

Description

sp.bubble() is the unified entry point for the entire bubble-chart family. The variant keyword selects the rendering strategy — all other arguments remain consistent across variants. A bubble chart extends a 2D scatter plot with a third numeric dimension represented as bubble area (not radius), following best practices for perceptual accuracy.

Parameters

ParameterUsed by variants
categoriescategorical, labeled, outlined
color_hexbasic, labeled, negative, outlined
color_highgradient, negative
color_lowgradient, negative
color_valuesgradient
gridlinesall
hoverall
labelsbasic, deluxe, gradient, labeled, negative, outlined, plasma
palettecategorical, labeled, outlined
sizesgradient, negative
stroke_widthbasic, categorical, gradient, labeled, negative, outlined
titleall
widthcategorical, gradient, negative, outlined
x_labelall
x_valuesall
y_labelall
y_valuesall

Returns

Chart — object with .html property and .show() method.



Histogram Charts

Signature

sp.histogram(title, values, *, variant="basic", bins=0, overlay_values=None, color_groups=None, series_names=None, **kwargs) -> Chart

Description

sp.histogram() is the unified entry point for the entire histogram family. The variant keyword selects the rendering strategy — every other argument keeps the same name across variants. Histograms are the canonical way to visualize the distribution of a single numeric variable; SeraPlot adds horizontal layout, density normalization, cumulative distribution, stacked groups, A/B overlay and step outline — all in pure Rust SVG, thousands of times faster than Plotly.

Parameters

ParameterUsed by variants
binsall
categoriesoverlay, stacked
colorbasic, cumulative, horizontal, normalized, overlay, step
count_scalebasic
gapbasic, deluxe, horizontal, normalized, overlay, stacked
gridlinesall
heightall
hoverall
opacitybasic, cumulative, horizontal, normalized
overlay_colorbasic, overlay
overlay_valuesbasic, overlay
paletteoverlay, stacked
series_namesbasic, overlay
show_countsbasic, deluxe, horizontal
sort_orderbasic
stroke_widthstep
titleall
valuesall
widthall
x_labelbasic, cumulative, horizontal, normalized, overlay, stacked, step
y_labelbasic, cumulative, horizontal, normalized, overlay, stacked, step

Returns

Chart — object with .html property and .show() method.


Signature

sp.histogram(title, values, *, variant="basic", bins=0, overlay_values=None, color_groups=None, series_names=None, **kwargs) -> Chart

Description

sp.histogram() est le point d'entrée unifié de toute la famille histogramme. Le mot-clé variant sélectionne la stratégie de rendu — tous les autres arguments gardent le même nom d'une variante à l'autre. Les histogrammes sont la façon canonique de visualiser la distribution d'une variable numérique ; SeraPlot ajoute layout horizontal, normalisation densité, distribution cumulative, groupes empilés, superposition A/B et contour en escalier — le tout en SVG Rust pur, des milliers de fois plus rapide que Plotly.

Paramètres

ParamètreUtilisé par variantes
binstoutes
categoriesoverlay, stacked
colorbasic, cumulative, horizontal, normalized, overlay, step
count_scalebasic
gapbasic, deluxe, horizontal, normalized, overlay, stacked
gridlinestoutes
heighttoutes
hovertoutes
opacitybasic, cumulative, horizontal, normalized
overlay_colorbasic, overlay
overlay_valuesbasic, overlay
paletteoverlay, stacked
series_namesbasic, overlay
show_countsbasic, deluxe, horizontal
sort_orderbasic
stroke_widthstep
titletoutes
valuestoutes
widthtoutes
x_labelbasic, cumulative, horizontal, normalized, overlay, stacked, step
y_labelbasic, cumulative, horizontal, normalized, overlay, stacked, step

Retour

Chart — objet exposant .html et .show().


Heatmap

Signature

sp.heatmap(title, labels=None, values=None, *, variant="basic", col_labels=None, **kwargs) -> Chart

Description

sp.heatmap() is the unified entry point for the entire heatmap family. The variant keyword selects the rendering strategy — every other argument stays consistent across variants. Cell colors are computed in pure Rust, no NumPy required. The matrix is passed as a flat list of length len(labels) * len(col_labels) (row-major).

Parameters

ParameterUsed by variants
col_labelsbubble, cluster, marginal, pivot, unequal
colorscaleconfusion
contour_levelscontour
discrete_stepsdiscrete
divergingbubble, marginal, pivot
flat_matrixbubble, cluster, marginal, pivot
heightbubble, marginal, pivot
hoverbubble, marginal, pivot
palettecategorical
row_labelsbubble, cluster, marginal, pivot, unequal
show_valuescategorical
titlebubble, marginal, pivot
widthbubble, marginal, pivot
x_widthsunequal
y_heightsunequal

Returns

Chart — object with .html property and .show() method.


Pie Charts

Signature

sp.pie(title, labels=None, values=None, *, variant="basic", series=None, **kwargs) -> Chart

Description

sp.pie() is the unified entry point for the entire pie-chart family. The variant keyword selects the rendering strategy — all other arguments remain consistent across variants.

Parameters

ParameterUsed by variants
center_subtextkpi, nested, proportional
center_textkpi, nested, proportional
donutnested, proportional, subplots
gridlinesproportional
heightnested, proportional, subplots
hoverproportional
labelsnested, proportional, subplots
legend_positionproportional
min_label_fracproportional
paletteproportional, subplots
patternproportional
proportionalproportional, subplots
pullbasic, donut, exploded, kpi, pattern, proportional, semi
secondary_labelsnested, proportional
secondary_valuesnested, proportional
seriesproportional, subplots
show_pctproportional
sort_orderproportional
subplot_colsproportional, subplots
subplot_titlesproportional, subplots
titlenested, proportional, subplots
valuesexploded, kpi, nested, proportional
variantproportional
widthnested, proportional, subplots
x_labelproportional
y_labelproportional

Returns

Chart — object with .html property and .show() method.


Box Plot

Signature

sp.boxplot(title, labels=None, values=None, *, variant="basic", series=None, **kwargs) -> Chart

Description

sp.boxplot() is the unified entry point for the entire box-plot family. The variant keyword selects the rendering strategy — every other argument stays consistent across variants. Quartiles, 1.5×IQR whiskers and outliers are computed in pure Rust without NumPy or pandas.

Parameters

ParameterUsed by variants
boxen_depthletter_value
category_labelsbasic, grouped, horizontal, letter_value, rainbow, strip, violin
fill_opacitybasic, grouped, horizontal, rainbow, violin
gridlinesbasic, grouped, horizontal, letter_value, rainbow, strip, violin
heighthorizontal
hoverbasic, grouped, horizontal, letter_value, rainbow, strip, violin
jitterbasic, strip
notchbasic, grouped, outliers, points, rainbow, violin
palettebasic, grouped, horizontal, letter_value, rainbow, strip, violin
seriesgrouped
series_namesgrouped
show_pointsbasic, notched
sort_orderbasic, horizontal, letter_value, rainbow, strip, violin
stroke_widthbasic, grouped, horizontal, rainbow, violin
titlebasic, grouped, horizontal, letter_value, rainbow, strip, violin
valuesbasic, horizontal, letter_value, rainbow, strip, violin
widthhorizontal
x_labelbasic, grouped, horizontal, letter_value, rainbow, strip, violin
y_labelbasic, grouped, horizontal, letter_value, rainbow, strip, violin

Returns

Chart — object with .html property and .show() method.


Violin Plot

Signature

sp.violin(title, labels=None, values=None, *, variant="box", **kwargs) -> Chart

Description

sp.violin() is the unified entry point for the entire violin-plot family. The variant keyword selects the rendering strategy — every other argument stays consistent across variants. The kernel-density estimation, quartiles and statistics are computed in pure Rust, no NumPy or pandas required.

Parameters

ParameterUsed by variants
bandwidthaurora, basic, crystal, deluxe, half, horizontal, mean, points, quartile, rainbow, split, with_box
categoriesall
fill_opacityaurora, basic, deluxe, half, horizontal, mean, points, quartile, rainbow, split, with_box
gridlinesall
hoverall
jitterpoints, strip
kde_stepsaurora, basic, crystal, deluxe, half, horizontal, mean, points, quartile, rainbow, split, with_box
palettebasic, half, horizontal, mean, points, quartile, split, strip, with_box
sort_orderall
stroke_widthaurora, basic, deluxe, half, horizontal, mean, points, quartile, rainbow, split, with_box
titleall
valuesall
x_labelall
y_labelall

Returns

Chart — object with .html property and .show() method.


KDE — Kernel Density Estimate

Signature

sp.kde(title, values, *, variant="basic", categories=None, bandwidth=0.0, filled=True, fill_opacity=50, bins=30, n_points=80, palette=None, **kwargs) -> Chart

Description

sp.kde() is the unified entry point for the entire Kernel Density Estimate family. The variant keyword selects the rendering strategy — every other argument keeps the same name across variants. KDE produces a smooth, continuous density estimate from a sample of points using a Gaussian kernel with Scott's rule for automatic bandwidth selection. SeraPlot renders the curves as pure Rust SVG, with native multi-series, normalization, CDF, rug, histogram overlay and gradient fills.

Parameters

ParameterUsed by variants
bandwidthall
binshistogram
fill_opacitybasic, normalized, rug, stepped
filledbasic, normalized, rug
gridlinesall
heightall
hoverall
n_pointsall
paletteall
titleall
widthall
x_labelall
y_labelall

Returns

Chart — object with .html property and .show() method.


Signature

sp.kde(title, values, *, variant="basic", categories=None, bandwidth=0.0, filled=True, fill_opacity=50, bins=30, n_points=80, palette=None, **kwargs) -> Chart

Description

sp.kde() est le point d'entrée unifié pour toute la famille KDE (Kernel Density Estimate). Le mot-clé variant sélectionne la stratégie de rendu — tous les autres arguments conservent le même nom d'une variante à l'autre. La KDE produit une estimation de densité continue lissée à partir d'un échantillon de points avec un noyau gaussien et la règle de Scott pour le choix automatique de la bande passante. SeraPlot rend les courbes en SVG Rust natif, avec multi-séries, normalisation, CDF, rug, histogramme superposé et remplissage en dégradé.

Paramètres

ParamètreUtilisé par variantes
bandwidthtoutes
binshistogram
fill_opacitybasic, normalized, rug, stepped
filledbasic, normalized, rug
gridlinestoutes
heighttoutes
hovertoutes
n_pointstoutes
palettetoutes
titletoutes
widthtoutes
x_labeltoutes
y_labeltoutes

Retour

Chart — objet avec propriété .html et méthode .show().


Ridgeline — Joyplot / Stacked KDE

Signature

sp.ridgeline(title, categories, values, *, variant="basic", overlap=0.5, bandwidth=0.0, n_points=60, fill_opacity=56, palette=None, **kwargs) -> Chart

Description

sp.ridgeline() is the unified entry point for the entire ridgeline family — also known as joyplot. The variant keyword selects the rendering strategy — every other argument keeps the same name across variants. A ridgeline plot stacks one KDE curve per category along a shared X axis with a controllable vertical overlap, making it ideal to compare distributions across many groups (years, regions, segments…). SeraPlot renders everything in pure Rust SVG, with quartile/mean overlays, rug ticks, gradient fills and a built-in viridis colormap.

Parameters

ParameterUsed by variants
fill_opacitybasic, mean, quartiles, rug, spaced
heightdeluxe
palettebasic, gradient, heatmap, lines, mean, quartiles, rug, spaced
titledeluxe
widthdeluxe

Returns

Chart — object with .html property and .show() method.


Signature

sp.ridgeline(title, categories, values, *, variant="basic", overlap=0.5, bandwidth=0.0, n_points=60, fill_opacity=56, palette=None, **kwargs) -> Chart

Description

sp.ridgeline() est le point d'entrée unifié pour toute la famille ridgeline — aussi appelé joyplot. Le mot-clé variant sélectionne la stratégie de rendu — tous les autres arguments conservent le même nom d'une variante à l'autre. Un ridgeline empile une courbe KDE par catégorie sur un axe X partagé avec un recouvrement vertical réglable, idéal pour comparer des distributions à travers plusieurs groupes (années, régions, segments…). SeraPlot rend tout en SVG Rust natif, avec marqueurs quartiles/moyenne, ticks rug, dégradés et palette viridis intégrée.

Paramètres

ParamètreUtilisé par variantes
fill_opacitybasic, mean, quartiles, rug, spaced
heightdeluxe
palettebasic, gradient, heatmap, lines, mean, quartiles, rug, spaced
titledeluxe
widthdeluxe

Retour

Chart — objet avec propriété .html et méthode .show().


Radar — Spider / Star Chart

Signature

sp.radar(title, axes, series, *, series_names=None, variant="basic", filled=True, fill_opacity=50, palette=None, **kwargs) -> Chart

Description

sp.radar() is the unified entry point for the entire radar / spider / star chart family. The variant keyword selects the rendering strategy — every other argument keeps the same name across variants. Radar charts are ideal for multivariate comparison across 3+ axes — performance profiles, KPIs, skill maps, scoring systems. SeraPlot draws everything in pure Rust SVG with concentric grid rings, axis lines, automatic ring tick labels, optional legend and per-series palette colors. The polar-bar variant turns the chart into a categorical polar histogram, the stacked variant builds a cumulative composition view.

Parameters

ParameterUsed by variants
axesdeluxe
fill_opacitybasic, filled, polar_bar, stacked
heightdeluxe
paletteall
seriesfilled, polar_bar, stacked
titledeluxe
widthdeluxe

Returns

Chart — object with .html property and .show() method.


Signature

sp.radar(title, axes, series, *, series_names=None, variant="basic", filled=True, fill_opacity=50, palette=None, **kwargs) -> Chart

Description

sp.radar() est le point d'entrée unifié pour toute la famille radar / spider / star. Le mot-clé variant sélectionne la stratégie de rendu — tous les autres arguments conservent le même nom d'une variante à l'autre. Le radar est idéal pour comparer plusieurs séries sur 3 axes ou plus — profils de performance, KPI, cartographie de compétences, systèmes de notation. SeraPlot dessine tout en SVG Rust natif avec anneaux de grille concentriques, axes, labels automatiques de graduation, légende optionnelle et couleurs de palette par série. La variante polar_bar transforme le radar en histogramme polaire catégoriel, la variante stacked construit une vue de composition cumulative.

Paramètres

ParamètreUtilisé par variantes
axesdeluxe
fill_opacitybasic, filled, polar_bar, stacked
heightdeluxe
palettetoutes
seriesfilled, polar_bar, stacked
titledeluxe
widthdeluxe

Retour

Chart — objet avec propriété .html et méthode .show().


Slope — Before / After Comparison Chart

Signature

sp.slope(title, labels, left, right, *, variant="basic", left_label="Before", right_label="After", palette=None, show_text=True, **kwargs) -> Chart

Description

sp.slope() renders the entire slope-chart family: two parallel value axes (left / right) with one connector per row. The variant keyword swaps the connector style without changing any other parameter. Slope charts excel at before/after comparisons, A/B test outcomes, ranking shifts, KPI changes between periods, and any pair-wise change across many entities.

Parameters

ParameterUsed by variants
left_labeldiverging
palettebumps, monochrome
right_labeldiverging
show_textbasic, bumps, curved, highlighted, monochrome, stepped, thick
widthdiverging

Returns

Chart — object with .html property and .show() method.


Tips

  • Use sort_order="asc" / "desc" to reorder rows by left value before drawing.
  • The "diverging" and "thick" variants encode magnitude visually — perfect for executive summaries.
  • For rank shifts (positions in a league), prefer "bumps" rather than "basic".
  • Combine palette= with "monochrome" to match brand colours per category.

Signature

sp.slope(title, labels, left, right, *, variant="basic", left_label="Before", right_label="After", palette=None, show_text=True, **kwargs) -> Chart

Description

sp.slope() produit toute la famille des slope charts : deux axes de valeurs parallèles (gauche / droite) avec un connecteur par ligne. Le mot-clé variant permute le style du connecteur sans changer aucun autre paramètre. Idéal pour comparer avant/après, résultats A/B, changements de classement, KPI entre périodes, et toute évolution par paire sur de nombreuses entités.

Paramètres

ParamètreUtilisé par variantes
left_labeldiverging
palettebumps, monochrome
right_labeldiverging
show_textbasic, bumps, curved, highlighted, monochrome, stepped, thick
widthdiverging

Retour

Chart — objet avec propriété .html et méthode .show().


Astuces

  • Utilisez sort_order="asc" / "desc" pour réordonner les lignes selon left avant le rendu.
  • Les variantes "diverging" et "thick" encodent visuellement la magnitude — parfaites pour un résumé exécutif.
  • Pour les changements de rang (positions dans un classement), préférez "bumps" à "basic".
  • Combinez palette= avec "monochrome" pour aligner les couleurs sur les catégories de marque.

Funnel — Conversion / Pipeline Chart

Signature

sp.funnel(title, labels, values, *, variant="basic", palette=None, show_text=True, **kwargs) -> Chart

Description

sp.funnel() renders the entire funnel-chart family: a stacked sequence of stages where each step’s width encodes a value. The variant keyword switches the geometry without changing any other parameter. Funnels are the standard for conversion analytics (visitors → signups → paid), recruiting pipelines, sales pipelines, process drop-off and any descending-cohort analysis.

Parameters

ParameterUsed by variants
paletteall
show_textall
widthall

Returns

Chart — object with .html property and .show() method.


Tips

  • Sort stages descending before passing them in (or use sort_order="desc").
  • Use "conversion" when the audience cares about stage-to-stage retention rate.
  • The "pyramid" variant works best when values follow a steep decay.
  • For broad audiences, "chevron" reads as a sales pipeline more naturally than the trapezoid.

Signature

sp.funnel(title, labels, values, *, variant="basic", palette=None, show_text=True, **kwargs) -> Chart

Description

sp.funnel() produit toute la famille des entonnoirs : une séquence d’étapes empilées dont la largeur encode une valeur. Le mot-clé variant permute la géométrie sans changer aucun autre paramètre. Standard pour l’analyse de conversion (visiteurs → inscrits → payants), pipelines de recrutement, pipelines commerciaux, fuites de processus et toute analyse de cohorte décroissante.

Paramètres

ParamètreUtilisé par variantes
palettetoutes
show_texttoutes
widthtoutes

Retour

Chart — objet avec propriété .html et méthode .show().


Astuces

  • Triez les étapes décroissantes avant de les passer (ou utilisez sort_order="desc").
  • Utilisez "conversion" quand l’audience s’intéresse au taux de rétention entre étapes.
  • La variante "pyramid" fonctionne mieux avec des valeurs en forte décroissance.
  • Pour un public large, "chevron" se lit plus naturellement comme un pipeline commercial qu’un trapèze.

Waterfall — Running-Total Bridge Chart

Signature

sp.waterfall(title, labels, values, *, variant="basic", show_text=True, **kwargs) -> Chart

Description

sp.waterfall() renders the entire waterfall-chart family: a sequence of bars where each step adds (positive) or subtracts (negative) from a running total. The variant keyword selects the geometry without touching any other parameter. Waterfalls are the standard for P&L bridges, variance analysis, cohort decomposition, fee/tax breakdowns and any "from A to B, what changed?" narrative.

Totals — set a value to 0 and use a label containing total, net, final, gross or ebitda to mark a subtotal bar; it is rendered with the totals color and anchored on the running sum.

Parameters

ParameterUsed by variants
gridlineshorizontal
heighthorizontal
show_textall
titlehorizontal
widthhorizontal

Returns

Chart — object with .html property and .show() method.


Signature

sp.waterfall(title, labels, values, *, variant="basic", show_text=True, **kwargs) -> Chart

Description

sp.waterfall() rassemble toute la famille des graphiques waterfall : une suite de barres ou chaque etape ajoute (positif) ou retranche (negatif) au cumul courant. Le mot-cle variant change la geometrie sans toucher aux autres parametres. Les waterfalls sont la reference pour les ponts de P&L, l analyse d ecarts, la decomposition de cohortes, le detail des frais/taxes et tout recit du type "de A vers B, qu est-ce qui a change ?".

Totaux — mettez la valeur a 0 et utilisez un libelle contenant total, net, final, gross ou ebitda pour marquer une barre de sous-total ; elle est rendue avec la couleur des totaux et ancree sur le cumul courant.

Parametres

ParametreTypeDefautDescription
titlestrrequisTitre du graphique
labelslist[str]requisLibelles des etapes (gauche -> droite)
valueslist[float]requisDeltas par etape (mettez 0 + libelle "total" pour les sous-totaux)
variantstr"basic"Variante geometrique (voir tableau)
show_textboolTrueAfficher les annotations de valeur au-dessus des barres
widthint900Largeur du canvas (px)
heightint480Hauteur du canvas (px)

Retour

Chart — objet avec une propriete .html et une methode .show().


Sunburst — Hierarchical Ring Chart

Signature

sp.sunburst(title, labels, parents, values, *, variant="basic", palette=None, **kwargs) -> Chart

Description

sp.sunburst() is the unified entry point for the entire sunburst-chart family. A sunburst represents a hierarchy as concentric rings: the innermost ring is the root, each outer ring is a deeper level, and angular size encodes value. The variant keyword selects the visual style without changing any other parameter. Sunbursts are the standard for visualizing nested taxonomies (org charts, file systems, market segmentation, expense categories, phylogenetic trees) and outperform classic pie charts as soon as a real hierarchy exists.

Hierarchy encodinglabels lists every node, parents gives the parent label of each node ("" for a root). Leaf values are taken from values; internal node values are auto-rolled-up from descendants when set to 0.

Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredNode labels (one per row)
parentslist[str]requiredParent label of each node ("" for roots)
valueslist[float]requiredLeaf values; internal zeros are auto-rolled-up
variantstr"basic"Visual style (see table)
palettelist[int]NonePer-root color palette (rotates if shorter)
widthint700Canvas width (px)
heightint700Canvas height (px)

Returns

Chart — object with .html property and .show() method.


Signature

sp.sunburst(title, labels, parents, values, *, variant="basic", palette=None, **kwargs) -> Chart

Description

sp.sunburst() est le point d entree unifie pour toute la famille des graphiques sunburst. Un sunburst represente une hierarchie sous forme d anneaux concentriques : l anneau interieur est la racine, chaque anneau exterieur est un niveau plus profond, et l angle code la valeur. Le mot-cle variant change le style sans toucher aux autres parametres. Les sunbursts sont la reference pour visualiser des taxonomies imbriquees (organigrammes, systemes de fichiers, segmentation marche, categories de depenses, arbres phylogenetiques) et surpassent le camembert des qu une vraie hierarchie existe.

Encodage de la hierarchielabels liste tous les noeuds, parents donne le libelle du parent de chaque noeud ("" pour une racine). Les valeurs des feuilles viennent de values ; les noeuds internes a 0 sont calcules automatiquement comme la somme de leurs descendants.

Parametres

ParametreTypeDefautDescription
titlestrrequisTitre du graphique
labelslist[str]requisLibelles des noeuds (un par ligne)
parentslist[str]requisParent de chaque noeud ("" pour les racines)
valueslist[float]requisValeurs feuilles ; zeros internes calcules auto
variantstr"basic"Style visuel (voir tableau)
palettelist[int]NonePalette couleurs par racine (rotation si trop courte)
widthint700Largeur du canvas (px)
heightint700Hauteur du canvas (px)

Retour

Chart — objet avec une propriete .html et une methode .show().


Treemap — Hierarchical Proportional Tiles

Signature

sp.treemap(title, labels, values, *, parents=None, variant="basic", palette=None, **kwargs) -> Chart

Description

sp.treemap() is the unified entry point for the entire treemap-chart family. A treemap divides a rectangle into proportional sub-rectangles whose area encodes value; when a parents list is given the layout becomes hierarchical (each parent gets its own block, leaves are squarified within). The variant keyword switches the visual style without touching the data. Treemaps are the standard for visualizing budgets, market cap, disk usage, portfolio weights, file systems and any 'whole = sum of parts' breakdown.

Hierarchical mode — pass parents (one parent label per leaf, can be empty string "" for a flat treemap). Internal totals are auto-computed from leaves. Sort leaves with the sort_order parameter ("desc" recommended).

Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredTile labels (one per leaf)
valueslist[float]requiredLeaf values (area)
parentslist[str]NoneParent label of each leaf ("" -> flat)
variantstr"basic"Visual style (see table)
palettelist[int]NoneCustom color palette (per parent or per tile)
sort_orderstr"none""none", "asc" or "desc" for leaves
widthint1100Canvas width (px)
heightint520Canvas height (px)

Returns

Chart — object with .html property and .show() method.


Signature

sp.treemap(title, labels, values, *, parents=None, variant="basic", palette=None, **kwargs) -> Chart

Description

sp.treemap() est le point d entree unifie pour toute la famille treemap. Un treemap decoupe un rectangle en sous-rectangles proportionnels dont l aire code la valeur ; lorsqu une liste parents est fournie le rendu devient hierarchique (chaque parent recoit son propre bloc, les feuilles y sont squarifiees). Le mot-cle variant change le style sans toucher aux donnees. Les treemaps sont la reference pour visualiser budgets, capitalisations boursieres, occupation disque, poids de portefeuille, systemes de fichiers et toute decomposition 'tout = somme des parties'.

Mode hierarchique — passez parents (un libelle parent par feuille, chaine vide "" pour un treemap plat). Les totaux internes sont auto-calcules. Triez les feuilles avec sort_order ("desc" recommande).

Parametres

ParametreTypeDefautDescription
titlestrrequisTitre du graphique
labelslist[str]requisLibelles des tuiles (un par feuille)
valueslist[float]requisValeurs feuilles (aire)
parentslist[str]NoneParent de chaque feuille ("" -> plat)
variantstr"basic"Style visuel (voir tableau)
palettelist[int]NonePalette de couleurs (par parent ou tuile)
sort_orderstr"none""none", "asc" ou "desc" pour les feuilles
widthint1100Largeur du canvas (px)
heightint520Hauteur du canvas (px)

Retour

Chart — objet avec une propriete .html et une methode .show().


Candlestick — OHLC Time Series

Signature

sp.candlestick(title, labels, open, high, low, close, *, variant="basic", palette=None, **kwargs) -> Chart

Description

sp.candlestick() is the unified entry point for the entire candlestick-chart family. A candlestick chart shows OHLC (Open, High, Low, Close) bars over time and is the de facto standard for financial markets, crypto, commodities, energy spot prices and any time-series with intra-period spread. The variant keyword switches the visual style without touching the data — including derived views like Heikin-Ashi smoothing, close-only line, mountain area and high-low range bars.

Color convention — by default green = up (close >= open) and red = down. Override with palette=[up_color, down_color]. Bars are rendered left-to-right in input order; use sort_order="asc" to sort by close price.

Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredPeriod labels (e.g. dates)
openlist[float]requiredOpening price per period
highlist[float]requiredHighest price per period
lowlist[float]requiredLowest price per period
closelist[float]requiredClosing price per period
variantstr"basic"Visual style (see table)
palettelist[int]None[up_color, down_color] (defaults: green/red)
gridlinesboolFalseHorizontal price gridlines
x_labelstr""X-axis label
y_labelstr""Y-axis label
sort_orderstr"none""none", "asc", "desc" (by close)
widthint1100Canvas width (px)
heightint500Canvas height (px)

Returns

Chart — object with .html property and .show() method.


Signature

sp.candlestick(title, labels, open, high, low, close, *, variant="basic", palette=None, **kwargs) -> Chart

Description

sp.candlestick() est le point d entree unifie pour toute la famille des chandeliers. Un graphique en chandeliers affiche des barres OHLC (Ouverture, Haut, Bas, Cloture) dans le temps et constitue le standard de fait pour les marches financiers, la crypto, les matieres premieres, le spot energie et toute serie temporelle avec spread intra-periode. Le mot-cle variant change le style sans toucher aux donnees — y compris des vues derivees comme le lissage Heikin-Ashi, la ligne de cloture, l aire mountain et les barres haut-bas.

Convention de couleur — par defaut vert = hausse (close >= open) et rouge = baisse. Surchargez avec palette=[couleur_hausse, couleur_baisse]. Les barres sont rendues de gauche a droite dans l ordre d entree ; sort_order="asc" pour trier par prix de cloture.

Parametres

ParametreTypeDefautDescription
titlestrrequisTitre du graphique
labelslist[str]requisLibelles de periode (ex. dates)
openlist[float]requisPrix d ouverture par periode
highlist[float]requisPrix le plus haut par periode
lowlist[float]requisPrix le plus bas par periode
closelist[float]requisPrix de cloture par periode
variantstr"basic"Style visuel (voir tableau)
palettelist[int]None[hausse, baisse] (defaut : vert/rouge)
gridlinesboolFalseLignes de grille horizontales
x_labelstr""Libelle axe X
y_labelstr""Libelle axe Y
sort_orderstr"none""none", "asc", "desc" (par cloture)
widthint1100Largeur du canvas (px)
heightint500Hauteur du canvas (px)

Retour

Chart — objet avec une propriete .html et une methode .show().


Dumbbell - Before / After Two-Point Comparison

Signature

sp.dumbbell(title, labels, start, end, *, variant="basic", series_name_start="Start", series_name_end="End", **kwargs) -> Chart

Description

sp.dumbbell() is the unified entry point for the dumbbell-chart family. Each row plots two values - typically a before and an after - linked by a connector, making it the chart of choice for change, gap or comparison-over-time analyses (salary equity, turnaround KPIs, A/B uplifts, etc.). The variant keyword switches the visual treatment without touching the data.

Parameters

ParameterUsed by variants
series_namesall

Returns

Chart - object with .html property and .show() method.


Signature

sp.dumbbell(title, labels, start, end, *, variant="basic", series_name_start="Start", series_name_end="End", **kwargs) -> Chart

Description

sp.dumbbell() est le point d entree unique pour la famille dumbbell. Chaque ligne montre deux valeurs - typiquement avant/apres - reliees par un connecteur, ce qui en fait le choix naturel pour visualiser un changement, un ecart ou une evolution (equite salariale, KPIs de redressement, uplifts A/B, etc.). Le mot-cle variant change le style visuel sans toucher aux donnees.

Parametres

ParametreTypeDefautDescription
titlestrrequisTitre du graphique
labelslist[str]requisLibelles de ligne
startlist[float]requisValeurs de depart
endlist[float]requisValeurs d arrivee
variantstr"basic"Style visuel (voir tableau)
series_name_startstr"Start"Label legende serie depart
series_name_endstr"End"Label legende serie arrivee
palettelist[int]NonePalette personnalisee: [c_start, c_end, ...]
sort_orderstr"none""none", "asc" or "desc"
widthint1000Largeur (px)
heightint500Hauteur (px)

Retour

Chart - objet avec propriete .html et methode .show().


Bullet - Compact KPI vs Target

Signature

sp.bullet(title, labels, values, *, targets=None, max_vals=None, ranges=None, comparisons=None, variant="basic", **kwargs) -> Chart

Description

sp.bullet() is the unified entry point for the bullet-chart family. Inspired by Edward Tufte, a bullet packs an actual value, a target, qualitative ranges and a scale into a single horizontal row - perfect for KPI dashboards where space is precious. The variant keyword switches the visual treatment (zones, traffic light, thermometer, progress pill, dot, ghost-bar comparison) without touching the data.

Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredRow labels
valueslist[float]requiredActual values
variantstr"basic"Visual style (see table)
targetslist[float]NoneTarget tick value per row
max_valslist[float]NonePer-row scale maximum (auto if 0)
rangeslist[float]NoneQualitative range threshold per row
comparisonslist[float]NoneComparison values for compare variant
widthint800Canvas width (px)
heightint300Canvas height (px, auto-grows with rows)

Returns

Chart - object with .html property and .show() method.


Signature

sp.bullet(title, labels, values, *, targets=None, max_vals=None, ranges=None, comparisons=None, variant="basic", **kwargs) -> Chart

Description

sp.bullet() est le point d entree unique pour la famille bullet. Inspire par Edward Tufte, le bullet condense valeur, cible, zones qualitatives et echelle dans une seule ligne horizontale - parfait pour des dashboards KPIs serres. Le mot-cle variant change l aspect (zones, feu tricolore, thermometre, pillule de progression, point, comparaison par barre fantome) sans toucher aux donnees.

Parametres

ParametreTypeDefautDescription
titlestrrequisTitre du graphique
labelslist[str]requisLibelles de ligne
valueslist[float]requisValeurs reelles
variantstr"basic"Style visuel (voir tableau)
targetslist[float]NoneValeur cible par ligne
max_valslist[float]NoneMaximum d echelle par ligne (auto si 0)
rangeslist[float]NoneSeuil de zone qualitative par ligne
comparisonslist[float]NoneValeurs de comparaison pour la variante compare
widthint800Largeur (px)
heightint300Hauteur (px, auto si trop petite)

Retour

Chart - objet avec propriete .html et methode .show().


Gauge - Single-Value Arc Indicator

Signature

sp.gauge(title, *, value, min_val=0.0, max_val=100.0, label="", variant="basic", comparison=0.0, **kwargs) -> Chart

Description

sp.gauge() is the unified entry point for the gauge family. A gauge maps a single scalar to a colored arc with optional thresholds - perfect for status / health / utilization KPIs. The variant keyword switches the geometry (half, three-quarter, full ring), the embellishments (needle, ticks, glow) and the layering (single arc vs. concentric arcs for value-vs-target).

Parameters

ParameterUsed by variants
comparisonconcentric
max_valarc270, concentric, tick
min_valarc270, tick
valueconcentric, sleek

Returns

Chart - object with .html property and .show() method.


Signature

sp.gauge(title, *, value, min_val=0.0, max_val=100.0, label="", variant="basic", comparison=0.0, **kwargs) -> Chart

Description

sp.gauge() est le point d entree unique pour la famille jauge. Une jauge associe un scalaire unique a un arc colore avec des seuils optionnels - parfait pour des KPIs de statut / sante / utilisation. Le mot-cle variant change la geometrie (demi, trois-quart, anneau complet), les ornements (aiguille, ticks, glow) et la composition (arc simple ou arcs concentriques pour valeur-vs-cible).

Parametres

ParametreTypeDefautDescription
titlestrrequisTitre du graphique
valuefloatrequisValeur courante a afficher
min_valfloat0.0Minimum de l echelle
max_valfloat100.0Maximum de l echelle
variantstr"basic"Style visuel (voir tableau)
labelstr""Sous-libelle sous la valeur
comparisonfloat0.0Valeur de comparaison (pour concentric)
seuilslist[(float,int)]None[(value, color_hex), ...] seuils
widthint400Largeur (px)
heightint300Hauteur (px)

Retour

Chart - objet avec propriete .html et methode .show().


Lollipop - Categorical Value Sticks

## Signature

sp.lollipop(title, labels, values, *, variant="basic", color_groups=None, highlight_index=-1, **kwargs) -> Chart

Description

sp.lollipop() is the unified entry point for the lollipop family. Each item becomes a thin stick capped by a dot - lighter ink than a bar chart for the same ranking, and the family includes circular, diverging, focused and grouped editorial layouts (the Office variant reproduces the season-rating panel pattern).

Parameters

ParameterUsed by variants
color_hexhighlight
gridlinesbasic, cleveland, highlight, office
heightcircular
highlight_indexhighlight
paletteoffice
show_valuesbasic, cleveland, diverging
titlecircular
widthcircular
y_labelbasic, diverging, highlight, office

Returns

Chart - object with .html property and .show() method.


Signature

sp.lollipop(title, labels, values, *, variant="basic", color_groups=None, highlight_index=-1, **kwargs) -> Chart

Description

sp.lollipop() est le point d entree unique pour la famille lollipop. Chaque item devient un baton fin termine par un point - moins d encre qu un bar chart pour le meme classement, et la famille couvre des layouts circulaires, divergents, focalises et editoriaux groupes (la variante Office reproduit le motif des saisons IMDb de The Office).

Parametres

ParametreTypeDefautDescription
titlestrrequisTitre du graphique
labelslist[str]requisLibelles categoriels (un par baton)
valueslist[float]requisValeur par libelle
variantstr"basic"Style visuel (voir tableau)
color_groupslist[str]NoneGroupe par item - active le groupage Office
highlight_indexint-1Index a mettre en avant (Highlight); -1 = auto-max
color_hexint0x6366F1Couleur par defaut
palettelist[int]NonePalette personnalisee
show_valuesboolFalseAfficher la valeur a cote de chaque point
gridlinesboolFalseActiver la grille de fond
sort_orderstr"none""none" / "asc" / "desc" / "alpha"
widthint900Largeur (px)
heightint480Hauteur (px)

Retour

Chart - objet avec propriete .html et methode .show().


Parallel Coordinates - Multivariate Profile Lines

Signature

sp.build_parallel(title, axes, series, *, variant="basic", **kwargs) -> Chart

Description

sp.build_parallel() renders a parallel-coordinates chart - one vertical axis per dimension, one polyline per row. Six variants cover the classical use cases: straight lines, smooth Bezier curves, categorical coloring, single-row highlight, density-blended overlay, and gradient coloring driven by any axis. Perfect for high-dimensional EDA, profile comparison, and class separability inspection.

Parameters

ParameterUsed by variants
axesarc, deluxe, gradient, ribbon
categoriescategorical
color_axisgradient
heightarc, deluxe, ribbon
highlight_indexhighlight
palettearc, basic, categorical, deluxe, density, highlight, ribbon, smooth
series_namesall
series_valuesall
titlearc, ribbon
widtharc, categorical, deluxe, gradient, ribbon

Returns

Chart - object with .html property and .show() method.


Signature

sp.build_parallel(title, axes, series, *, variant="basic", **kwargs) -> Chart

Description

sp.build_parallel() rend un graphique parallel-coordinates - un axe vertical par dimension, une polyligne par ligne. Six variantes couvrent les cas classiques : lignes droites, courbes Bezier, couleur par categorie, mise en avant d une ligne, overlay de densite, et degrade pilote par un axe. Ideal pour l EDA haute-dimension, la comparaison de profils, et l inspection de separabilite de classes.

Parametres

ParametreTypeDefautDescription
titlestrrequisTitre du graphique
axeslist[str]requisEtiquettes des axes (gauche vers droite)
serieslist[list[float]]requisProfils - une liste interne par axe
variantstr"basic"Style de rendu (voir tableau)
series_nameslist[str]NoneNoms optionnels par ligne (hover/legende)
category_indiceslist[int]NoneId de categorie par ligne (variant categorical)
highlight_indexint-1Ligne a mettre en avant (variant highlight)
color_axisint-1Index de l axe pilotant la couleur (variant gradient)
palettelist[int]NonePalette personnalisee
widthint1000Largeur (px)
heightint500Hauteur (px)

Retour

Chart - objet avec propriete .html et methode .show().

Word Cloud - Six Rendering Architectures

Signature

sp.build_wordcloud(title, words, frequencies, *, variant="basic", shape="rect", **kwargs) -> Chart

Description

sp.build_wordcloud() packs weighted tokens into six rendering architectures. Basic is the canonical spiral packer driven by a parametric shape= mask (rect, circle, heart, bird, glasses, diamond, star). Bubble gives each word its own color-filled disc sized by frequency - a packed-bubble layout. Context is an InfraNodus-style text-network cloud: words positioned by a force-directed layout driven by co-occurrence edges so semantically close words cluster spatially, colored by community. Image accepts any binary pixel mask (logo, icon, photo). LabelMap draws a datamapplot-style clustered scatter with leader-line labels. Network renders a keyword co-occurrence graph with bezier-curved edges.

Shapes (for variant basic)

The basic variant accepts a shape= argument that selects the silhouette mask:

ShapeAliasesDescription
"rect"rect / rectangle / box / defaultRectangular Archimedean spiral - the textbook word cloud.
"circle"circle / round / disk / ballWords packed inside a perfect disc.
"heart"heart / love / valentineCardioid heart silhouette.
"bird"bird / twitter / tweet / iconComposite-disk stylised bird silhouette.
"glasses"glasses / sunglasses / shades / specsSunglasses silhouette (two ellipses + bridge).
"diamond"diamond / rhombus / lozengeRotated square / rhombus silhouette.
"star"star / starburst / 5-point5-pointed star silhouette.

Parameters

ParameterUsed by variants
heightall
hoverall
paletteall
titleall
widthall

Returns

Chart - object with .html property and .show() method.


Signature

sp.build_wordcloud(title, words, frequencies, *, variant="basic", shape="rect", **kwargs) -> Chart

Description

sp.build_wordcloud() propose six architectures de rendu. Basic est le packer spirale canonique pilote par un masque shape= (rect, circle, heart, bird, glasses, diamond, star). Bubble donne a chaque mot un disque colore dimensionne par frequence - un layout bubble-packed. Context est un nuage texte-reseau style InfraNodus : mots positionnes par layout force-dirige base sur les aretes de co-occurrence, colores par communaute. Image accepte n importe quel masque binaire de pixels. LabelMap dessine un scatter clusterise style datamapplot avec etiquettes en lignes de rappel. Network rend un graphe de co-occurrence de mots-cles avec aretes bezier.

Formes (pour la variante `basic`)

La variante basic accepte un argument shape= :

FormeAliasDescription
"rect"rect / rectangle / box / defaultRectangular Archimedean spiral - the textbook word cloud.
"circle"circle / round / disk / ballWords packed inside a perfect disc.
"heart"heart / love / valentineCardioid heart silhouette.
"bird"bird / twitter / tweet / iconComposite-disk stylised bird silhouette.
"glasses"glasses / sunglasses / shades / specsSunglasses silhouette (two ellipses + bridge).
"diamond"diamond / rhombus / lozengeRotated square / rhombus silhouette.
"star"star / starburst / 5-point5-pointed star silhouette.

Parametres

ParametreTypeDefautDescription
titlestrrequisTitre du graphique
wordslist[str]requisTokens (toutes variantes sauf labelmap)
frequencieslist[float]requisPoids par mot (controle la taille)
variantstr"basic"Mode de rendu (voir Variantes)
shapestr"rect"Sous-forme pour basic (voir Formes)
masklist[int]NoneMasque binaire (variante image) - row-major, 1=interieur
mask_widthint0Largeur du masque (variante image)
mask_heightint0Hauteur du masque (variante image)
points_xlist[float]NoneCoords x du scatter (variante labelmap)
points_ylist[float]NoneCoords y du scatter (variante labelmap)
category_indiceslist[int]NoneId de cluster par point/mot (labelmap, context)
cluster_labelslist[str]NoneEtiquette par cluster (variante labelmap)
edges_ilist[int]NoneIndices source des aretes (variantes network, context)
edges_jlist[int]NoneIndices cible des aretes (variantes network, context)
edges_wlist[float]NonePoids des aretes (variantes network, context)
min_fontfloat12.0Plus petite taille de police rendue
max_fontfloat72.0Plus grande taille de police rendue
palettelist[int]NonePalette personnalisee
bg_colorstrautoCouleur de fond
widthint900Largeur du canvas (px)
heightint500Hauteur du canvas (px)

Retour

Chart - objet avec propriete .html et methode .show().

3D Charts

SeraPlot provides 17 three-dimensional chart types rendered with full WebGL acceleration.

ChartFunction
Scatter 3Dscatter3d()
Bar 3Dbar3d()
Line 3Dline3d()
Radar 3Dradar3d()
Lollipop 3Dlollipop3d()
KDE 3Dkde3d()
Ridgeline 3Dridgeline3d()
Bubble 3Dbubble3d()
Pie 3Dpie3d()
Violin 3Dviolin3d()
Heatmap 3Dheatmap3d()
Candlestick 3Dcandlestick3d()
Dumbbell 3Ddumbbell3d()
Funnel 3Dfunnel3d()
Sunburst 3Dsunburst3d()
Stacked Bar 3Dstacked_bar3d()
Globe 3Dglobe3d()

SeraPlot propose 17 types de graphiques tridimensionnels rendus avec acc\u00e9l\u00e9ration WebGL compl\u00e8te.

GraphiqueFonction
Nuage de points 3Dscatter3d()
Barres 3Dbar3d()
Courbe 3Dline3d()
Radar 3Dradar3d()
Sucette 3Dlollipop3d()
KDE 3Dkde3d()
Ridgeline 3Dridgeline3d()
Bulles 3Dbubble3d()
Camembert 3Dpie3d()
Violon 3Dviolin3d()
Heatmap 3Dheatmap3d()
Bougie 3Dcandlestick3d()
Halt\u00e8re 3Ddumbbell3d()
Entonnoir 3Dfunnel3d()
Sunburst 3Dsunburst3d()
Barres empil\u00e9es 3Dstacked_bar3d()
Globe 3Dglobe3d()

Scatter 3D

Signature

sp.build_scatter3d_chart(
    title: str,
    x: list[float],
    y: list[float],
    z: list[float],
    *,
    color_values: list[float] | None = None,
    color_labels: list[str] | None = None,
    series_names: list[str] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "X",
    y_label: str = "Y",
    z_label: str = "Z",
    hover_json: str | None = None,
    palette: list[int] | None = None,
) -> Chart

Aliases: sp.scatter3d


Description

GPU-accelerated 3D scatter plot rendered via WebGL. Handles millions of points at interactive frame rates.

Use color_values for a continuous color scale, or color_labels for categorical coloring.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
xlist[float]requiredX coordinates
ylist[float]requiredY coordinates
zlist[float]requiredZ coordinates
color_valueslist[float] | NoneNoneContinuous colormap values
color_labelslist[str] | NoneNoneCategorical color group labels
series_nameslist[str] | NoneNoneSeries legend names
bg_colorstr"#1a1a2e"Canvas background color
widthint900Canvas width
heightint600Canvas height
x_labelstr"X"X-axis label
y_labelstr"Y"Y-axis label
z_labelstr"Z"Z-axis label
hover_jsonstr | NoneNoneCustom hover JSON
palettelist[int] | NoneNoneCustom color palette

Returns

Chart


Performance

The renderer uses a single gl.drawArrays(POINTS, …) call per frame. Tested at 10 million points at 60 fps on a mid-range GPU.


Examples

3D scatter with categorical colors

import seraplot as sp
import random
n = 1000
x = [random.gauss(0, 1) for _ in range(n)]
y = [random.gauss(0, 1) for _ in range(n)]
z = [random.gauss(0, 1) for _ in range(n)]
groups = [random.choice(["A", "B", "C"]) for _ in range(n)]
chart = sp.build_scatter3d_chart(
    "3D Point Cloud",
    x_values=x, y_values=y, z_values=z,
    color_labels=groups,
    x_label="X", y_label="Y", z_label="Z",
)
const sp = require('seraplot');
import random
const n = 1000
const x = [random.gauss(0, 1) for _ in range(n)]
const y = [random.gauss(0, 1) for _ in range(n)]
const z = [random.gauss(0, 1) for _ in range(n)]
const groups = [random.choice(["A", "B", "C"]) for _ in range(n)]
const chart = sp.build_scatter3d_chart("3D Point Cloud",
x,
y,
{
    z_values: z,
    color_labels: groups,
    x_label: "X",
    y_label: "Y",
    z_label: "Z"
})
import * as sp from 'seraplot';
import random
const n: number = 1000
const x: number[] = [random.gauss(0, 1) for _ in range(n)]
const y: number[] = [random.gauss(0, 1) for _ in range(n)]
const z: number[] = [random.gauss(0, 1) for _ in range(n)]
const groups: string[] = [random.choice(["A", "B", "C"]) for _ in range(n)]
const chart = sp.build_scatter3d_chart("3D Point Cloud",
x,
y,
{
    z_values: z,
    color_labels: groups,
    x_label: "X",
    y_label: "Y",
    z_label: "Z"
})
▶ Live Preview

Signature

sp.build_scatter3d_chart(
    title: str,
    x: list[float],
    y: list[float],
    z: list[float],
    *,
    color_values: list[float] | None = None,
    color_labels: list[str] | None = None,
    series_names: list[str] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "X",
    y_label: str = "Y",
    z_label: str = "Z",
    hover_json: str | None = None,
    palette: list[int] | None = None,
) -> Chart

Aliases: sp.scatter3d


Description

Nuage de points 3D accéléré GPU via WebGL. Gère des millions de points à des fréquences d'images interactives.

Utilisez color_values pour une échelle de couleur continue, ou color_labels pour un coloriage catégoriel.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
xlist[float]requisCoordonnées X
ylist[float]requisCoordonnées Y
zlist[float]requisCoordonnées Z
color_valueslist[float] | NoneNoneValeurs de colormap continues
color_labelslist[str] | NoneNoneGroupes de couleur catégoriels
series_nameslist[str] | NoneNoneNoms des séries pour la légende
bg_colorstr"#1a1a2e"Couleur de fond
widthint900Largeur du canvas
heightint600Hauteur du canvas
x_labelstr"X"Étiquette de l'axe X
y_labelstr"Y"Étiquette de l'axe Y
z_labelstr"Z"Étiquette de l'axe Z
hover_jsonstr | NoneNoneJSON d'infobulle personnalisée
palettelist[int] | NoneNonePalette de couleurs

Retourne

Chart


Performance

Le moteur de rendu utilise un seul appel gl.drawArrays(POINTS, …) par frame. Testé avec 10 millions de points à 60 fps sur un GPU milieu de gamme.


Exemples

Nuage 3D avec couleurs catégorielles

import seraplot as sp
import random
n = 1000
x = [random.gauss(0, 1) for _ in range(n)]
y = [random.gauss(0, 1) for _ in range(n)]
z = [random.gauss(0, 1) for _ in range(n)]
groupes = [random.choice(["A", "B", "C"]) for _ in range(n)]
chart = sp.build_scatter3d_chart(
    "Nuage 3D",
    x_values=x, y_values=y, z_values=z,
    color_labels=groupes,
    x_label="X", y_label="Y", z_label="Z",
)
const sp = require('seraplot');
const n = 1000;
const x = Array.from({length: n}, () => Math.random() * 6 - 3);
const y = Array.from({length: n}, () => Math.random() * 6 - 3);
const z = Array.from({length: n}, () => Math.random() * 6 - 3);
const groupes = Array.from({length: n}, () => ["A","B","C"][Math.floor(Math.random()*3)]);
const chart = sp.build_scatter3d_chart("Nuage 3D", x, y, {
    z_values: z,
    color_labels: groupes,
    x_label: "X", y_label: "Y", z_label: "Z"
});
import * as sp from 'seraplot';
const n: number = 1000;
const x: number[] = Array.from({length: n}, () => Math.random() * 6 - 3);
const y: number[] = Array.from({length: n}, () => Math.random() * 6 - 3);
const z: number[] = Array.from({length: n}, () => Math.random() * 6 - 3);
const groupes: string[] = Array.from({length: n}, () => ["A","B","C"][Math.floor(Math.random()*3)]);
const chart = sp.build_scatter3d_chart("Nuage 3D", x, y, {
    z_values: z,
    color_labels: groupes,
    x_label: "X", y_label: "Y", z_label: "Z"
});
▶ Aperçu en direct

Bar Chart 3D

Signature

sp.build_bar3d_chart(
    title: str,
    labels: list[str],
    values: list[float],
    *,
    color_hex: int = 0x6366F1,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "",
    show_text: bool = False,
) -> Chart

Aliases: sp.bar3d


Description

3D bar chart rendering bars as extruded rectangular prisms on a WebGL canvas.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredBar labels
valueslist[float]requiredBar heights
color_hexint0x6366F1Single bar color
palettelist[int] | NoneNonePer-bar colors
bg_colorstr"#1a1a2e"Background color
widthint900Canvas width
heightint600Canvas height
x_labelstr""X-axis label
y_labelstr""Y-axis label
z_labelstr""Z-axis label
show_textboolFalseShow value labels

Returns

Chart


Examples

import seraplot as sp
chart = sp.build_bar3d_chart(
    "Sales by Product",
    x_values=[0.0, 1.0, 2.0, 3.0, 0.0, 1.0, 2.0, 3.0],
    y_values=[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0],
    z_values=[420.0, 380.0, 290.0, 510.0, 480.0, 420.0, 350.0, 590.0],
    x_label="Product",
    y_label="Year",
    z_label="Units",
)
const sp = require('seraplot');
const chart = sp.build_bar3d_chart("Sales by Product",
[0.0, 1.0, 2.0, 3.0, 0.0, 1.0, 2.0, 3.0],
[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0],
{
    z_values: [420.0, 380.0, 290.0, 510.0, 480.0, 420.0, 350.0, 590.0],
    x_label: "Product",
    y_label: "Year",
    z_label: "Units"
})
import * as sp from 'seraplot';
const chart = sp.build_bar3d_chart("Sales by Product",
[0.0, 1.0, 2.0, 3.0, 0.0, 1.0, 2.0, 3.0],
[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0],
{
    z_values: [420.0, 380.0, 290.0, 510.0, 480.0, 420.0, 350.0, 590.0],
    x_label: "Product",
    y_label: "Year",
    z_label: "Units"
})
▶ Live Preview

Signature

sp.build_bar3d_chart(
    title: str,
    labels: list[str],
    values: list[float],
    *,
    color_hex: int = 0x6366F1,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "",
    show_text: bool = False,
) -> Chart

Aliases: sp.bar3d


Description

Graphique en barres 3D rendant les barres comme des prismes rectangulaires extrudés sur un canvas WebGL.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
labelslist[str]requisÉtiquettes des barres
valueslist[float]requisHauteurs des barres
color_hexint0x6366F1Couleur unique des barres
palettelist[int] | NoneNoneCouleurs par barre
bg_colorstr"#1a1a2e"Couleur de fond
widthint900Largeur du canvas
heightint600Hauteur du canvas
x_labelstr""Étiquette de l'axe X
y_labelstr""Étiquette de l'axe Y
z_labelstr""Étiquette de l'axe Z
show_textboolFalseAfficher les étiquettes de valeur

Retourne

Chart


Exemples

import seraplot as sp

chart = sp.build_bar3d_chart(
    "Ventes par produit",
    x_values=[0.0, 1.0, 2.0, 3.0, 0.0, 1.0, 2.0, 3.0],
    y_values=[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0],
    z_values=[420.0, 380.0, 290.0, 510.0, 480.0, 420.0, 350.0, 590.0],
    x_label="Produit",
    y_label="Année",
    z_label="Unités",
)

Line Chart 3D

Signature

sp.build_line3d_chart(
    title: str,
    x: list[float],
    y: list[float],
    z: list[float],
    *,
    color_hex: int = 0x6366F1,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "X",
    y_label: str = "Y",
    z_label: str = "Z",
    series_names: list[str] | None = None,
    show_points: bool = True,
) -> Chart

Aliases: sp.line3d


Description

3D line chart connecting sequential points in 3D space. Useful for trajectories, time-series in 3D space, and parametric curves.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
xlist[float]requiredX coordinates
ylist[float]requiredY coordinates
zlist[float]requiredZ coordinates
color_hexint0x6366F1Line color
palettelist[int] | NoneNoneMulti-series colors
bg_colorstr"#1a1a2e"Background color
widthint900Canvas width
heightint600Canvas height
x_labelstr"X"X-axis label
y_labelstr"Y"Y-axis label
z_labelstr"Z"Z-axis label
series_nameslist[str] | NoneNoneSeries legend names
show_pointsboolTrueShow point markers

Returns

Chart


Examples

Helix trajectory

import seraplot as sp
import math
t = [i * 0.1 for i in range(100)]
x = [math.cos(v) for v in t]
y = [math.sin(v) for v in t]
z = t
chart = sp.build_line3d_chart(
    "Helix",
    x_values=x, y_values=y, z_values=z,
    x_label="cos(t)", y_label="sin(t)", z_label="t",
)
const sp = require('seraplot');
import math
const t = [i * 0.1 for i in range(100)]
const x = [math.cos(v) for v in t]
const y = [math.sin(v) for v in t]
const z = t
const chart = sp.build_line3d_chart("Helix",
x,
y,
{
    z_values: z,
    x_label: "cos(t)",
    y_label: "sin(t)",
    z_label: "t"
})
import * as sp from 'seraplot';
import math
const t: number[] = [i * 0.1 for i in range(100)]
const x: number[] = [math.cos(v) for v in t]
const y: number[] = [math.sin(v) for v in t]
const z = t
const chart = sp.build_line3d_chart("Helix",
x,
y,
{
    z_values: z,
    x_label: "cos(t)",
    y_label: "sin(t)",
    z_label: "t"
})
▶ Live Preview

Signature

sp.build_line3d_chart(
    title: str,
    x: list[float],
    y: list[float],
    z: list[float],
    *,
    color_hex: int = 0x6366F1,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "X",
    y_label: str = "Y",
    z_label: str = "Z",
    series_names: list[str] | None = None,
    show_points: bool = True,
) -> Chart

Aliases: sp.line3d


Description

Graphique en courbe 3D connectant des points séquentiels dans l'espace 3D. Utile pour les trajectoires, les séries temporelles 3D et les courbes paramétriques.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
xlist[float]requisCoordonnées X
ylist[float]requisCoordonnées Y
zlist[float]requisCoordonnées Z
color_hexint0x6366F1Couleur de la courbe
palettelist[int] | NoneNoneCouleurs multi-séries
bg_colorstr"#1a1a2e"Couleur de fond
widthint900Largeur du canvas
heightint600Hauteur du canvas
x_labelstr"X"Étiquette de l'axe X
y_labelstr"Y"Étiquette de l'axe Y
z_labelstr"Z"Étiquette de l'axe Z
series_nameslist[str] | NoneNoneNoms des séries pour la légende
show_pointsboolTrueAfficher les marqueurs de points

Retourne

Chart


Exemples

import seraplot as sp
import math

t = [i * 0.1 for i in range(100)]
x = [math.cos(v) for v in t]
y = [math.sin(v) for v in t]
z = t

chart = sp.build_line3d_chart(
    "Hélice",
    x_values=x, y_values=y, z_values=z,
    x_label="cos(t)", y_label="sin(t)", z_label="t",
)

Radar Chart 3D

Signature

sp.build_radar3d_chart(
    title: str,
    axes: list[str],
    series: list[list[float]],
    *,
    series_names: list[str] | None = None,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 700,
    height: int = 600,
    max_val: float | None = None,
    fill_opacity: float = 0.25,
) -> Chart

Aliases: sp.radar3d


Description

3D rendered radar (spider) chart. Same concept as the 2D radar but rendered in a WebGL 3D scene.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
axeslist[str]requiredAxis labels
serieslist[list[float]]requiredValues per series per axis
series_nameslist[str] | NoneNoneLegend names
palettelist[int] | NoneNoneSeries colors
bg_colorstr"#1a1a2e"Background color
widthint700Canvas width
heightint600Canvas height
max_valfloat | NoneNoneCommon scale maximum
fill_opacityfloat0.25Fill opacity

Returns

Chart


Examples

import seraplot as sp
chart = sp.build_radar3d_chart(
    "Skills Comparison 3D",
    axes=["Python", "Rust", "SQL", "ML", "DevOps"],
    series_values=[
        [9, 7, 8, 8, 6],
        [5, 10, 6, 4, 9],
    ],
    series_names=["Alice", "Bob"],
)
const sp = require('seraplot');
const chart = sp.build_radar3d_chart("Skills Comparison 3D",
["Python", "Rust", "SQL", "ML", "DevOps"],
{
    series_values: [[9, 7, 8, 8, 6], [5, 10, 6, 4, 9]],
    series_names: ["Alice", "Bob"]
})
import * as sp from 'seraplot';
const chart = sp.build_radar3d_chart("Skills Comparison 3D",
["Python", "Rust", "SQL", "ML", "DevOps"],
{
    series_values: [[9, 7, 8, 8, 6], [5, 10, 6, 4, 9]],
    series_names: ["Alice", "Bob"]
})
▶ Live Preview

Signature

sp.build_radar3d_chart(
    title: str,
    axes: list[str],
    series: list[list[float]],
    *,
    series_names: list[str] | None = None,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 700,
    height: int = 600,
    max_val: float | None = None,
    fill_opacity: float = 0.25,
) -> Chart

Aliases: sp.radar3d


Description

Graphique radar 3D (toile d'araignée). Même concept que le radar 2D mais rendu dans une scène WebGL.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
axeslist[str]requisÉtiquettes des axes
serieslist[list[float]]requisValeurs par série par axe
series_nameslist[str] | NoneNoneNoms de légende
palettelist[int] | NoneNoneCouleurs des séries
bg_colorstr"#1a1a2e"Couleur de fond
widthint700Largeur du canvas
heightint600Hauteur du canvas
max_valfloat | NoneNoneMaximum de l'échelle commune
fill_opacityfloat0.25Opacité du remplissage

Retourne

Chart


Exemples

import seraplot as sp

chart = sp.build_radar3d_chart(
    "Comparaison de compétences 3D",
    axes=["Python", "Rust", "SQL", "ML", "DevOps"],
    series_values=[
        [9, 7, 8, 8, 6],
        [5, 10, 6, 4, 9],
    ],
    series_names=["Alice", "Bob"],
)

Lollipop Chart 3D

Signature

sp.build_lollipop3d_chart(
    title: str,
    labels: list[str],
    values: list[float],
    *,
    color_hex: int = 0x6366F1,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "",
    show_text: bool = False,
) -> Chart

Aliases: sp.lollipop3d


Description

3D lollipop chart — stems and spheres rendered in a WebGL scene.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredCategory labels
valueslist[float]requiredValues per category
color_hexint0x6366F1Stem and sphere color
palettelist[int] | NoneNonePer-category colors
bg_colorstr"#1a1a2e"Background color
widthint900Canvas width
heightint600Canvas height
show_textboolFalseShow value labels

Returns

Chart


Examples

import seraplot as sp
chart = sp.build_lollipop3d_chart(
    "Monthly Sales 3D",
    x_values=[1.0, 2.0, 3.0, 4.0, 5.0],
    y_values=[0.0, 0.0, 0.0, 0.0, 0.0],
    z_values=[120.0, 95.0, 140.0, 110.0, 160.0],
)
const sp = require('seraplot');
const chart = sp.build_lollipop3d_chart("Monthly Sales 3D",
[1.0, 2.0, 3.0, 4.0, 5.0],
[0.0, 0.0, 0.0, 0.0, 0.0],
{
    z_values: [120.0, 95.0, 140.0, 110.0, 160.0]
})
import * as sp from 'seraplot';
const chart = sp.build_lollipop3d_chart("Monthly Sales 3D",
[1.0, 2.0, 3.0, 4.0, 5.0],
[0.0, 0.0, 0.0, 0.0, 0.0],
{
    z_values: [120.0, 95.0, 140.0, 110.0, 160.0]
})
▶ Live Preview

Signature

sp.build_lollipop3d_chart(
    title: str,
    labels: list[str],
    values: list[float],
    *,
    color_hex: int = 0x6366F1,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "",
    show_text: bool = False,
) -> Chart

Aliases: sp.lollipop3d


Description

Graphique en sucette 3D — tiges et sphères rendus dans une scène WebGL.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
labelslist[str]requisÉtiquettes des catégories
valueslist[float]requisValeurs par catégorie
color_hexint0x6366F1Couleur des tiges et sphères
palettelist[int] | NoneNoneCouleurs par catégorie
bg_colorstr"#1a1a2e"Couleur de fond
widthint900Largeur du canvas
heightint600Hauteur du canvas
show_textboolFalseAfficher les étiquettes de valeur

Retourne

Chart


Exemples

import seraplot as sp

chart = sp.build_lollipop3d_chart(
    "Ventes mensuelles 3D",
    x_values=[1.0, 2.0, 3.0, 4.0, 5.0],
    y_values=[0.0, 0.0, 0.0, 0.0, 0.0],
    z_values=[120.0, 95.0, 140.0, 110.0, 160.0],
)

KDE Chart 3D

Signature

sp.build_kde3d_chart(
    title: str,
    x: list[float],
    y: list[float],
    *,
    bandwidth: float = 1.0,
    resolution: int = 50,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "X",
    y_label: str = "Y",
    z_label: str = "Density",
) -> Chart

Aliases: sp.kde3d


Description

2D Kernel Density Estimation rendered as a 3D surface mesh over a grid. Visualizes the joint density of two variables.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
xlist[float]requiredX sample data
ylist[float]requiredY sample data
bandwidthfloat1.0KDE bandwidth factor
resolutionint50Grid resolution (n × n)
palettelist[int] | NoneNoneColor gradient palette
bg_colorstr"#1a1a2e"Background color
widthint900Canvas width
heightint600Canvas height
x_labelstr"X"X-axis label
y_labelstr"Y"Y-axis label
z_labelstr"Density"Z-axis label

Returns

Chart


Examples

import seraplot as sp
import random
values = (
    [random.gauss(-2, 1) for _ in range(200)] +
    [random.gauss(0, 0.8) for _ in range(200)] +
    [random.gauss(3, 1.2) for _ in range(200)]
)
categories = ["Group A"] * 200 + ["Group B"] * 200 + ["Group C"] * 200
chart = sp.build_kde3d_chart(
    "Density by Group",
    values,
    categories=categories,
)
const sp = require('seraplot');
import random
const values = (
    [random.gauss(-2, 1) for _ in range(200)] +
    [random.gauss(0, 0.8) for _ in range(200)] +
    [random.gauss(3, 1.2) for _ in range(200)]
)
const categories = ["Group A"] * 200 + ["Group B"] * 200 + ["Group C"] * 200
const chart = sp.build_kde3d_chart("Density by Group",
values,
{
    categories: categories
})
import * as sp from 'seraplot';
import random
const values = (
    [random.gauss(-2, 1) for _ in range(200)] +
    [random.gauss(0, 0.8) for _ in range(200)] +
    [random.gauss(3, 1.2) for _ in range(200)]
)
const categories: string[] = ["Group A"] * 200 + ["Group B"] * 200 + ["Group C"] * 200
const chart = sp.build_kde3d_chart("Density by Group",
values,
{
    categories: categories
})
▶ Live Preview

Signature

sp.build_kde3d_chart(
    title: str,
    x: list[float],
    y: list[float],
    *,
    bandwidth: float = 1.0,
    resolution: int = 50,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "X",
    y_label: str = "Y",
    z_label: str = "Density",
) -> Chart

Aliases: sp.kde3d


Description

Estimation par noyau 2D rendue comme une surface maillage 3D. Visualise la densité jointe de deux variables.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
xlist[float]requisDonnées X
ylist[float]requisDonnées Y
bandwidthfloat1.0Facteur de bande passante KDE
resolutionint50Résolution de la grille (n × n)
palettelist[int] | NoneNonePalette de gradient de couleur
bg_colorstr"#1a1a2e"Couleur de fond
widthint900Largeur du canvas
heightint600Hauteur du canvas
x_labelstr"X"Étiquette de l'axe X
y_labelstr"Y"Étiquette de l'axe Y
z_labelstr"Density"Étiquette de l'axe Z

Retourne

Chart


Exemples

import seraplot as sp
import random

x = [random.gauss(0, 1) for _ in range(400)]
y = [xi * 0.5 + random.gauss(0, 0.5) for xi in x]

chart = sp.build_kde3d_chart(
    "Densité jointe X vs Y",
    x=x, y=y,
    x_label="X", y_label="Y", z_label="Densité",
)

Ridgeline Chart 3D

Signature

sp.build_ridgeline3d_chart(
    title: str,
    categories: list[str],
    values: list[float],
    *,
    bandwidth: float = 1.0,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "Density",
) -> Chart

Aliases: sp.ridgeline3d


Description

Ridgeline chart in 3D — KDE surfaces per category arranged along the Y axis in a WebGL scene.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
categorieslist[str]requiredCategory labels
valueslist[float]requiredFlat concatenated sample data
bandwidthfloat1.0KDE bandwidth
palettelist[int] | NoneNonePer-ridge colors
bg_colorstr"#1a1a2e"Background
widthint900Canvas width
heightint600Canvas height
z_labelstr"Density"Z-axis label

Returns

Chart


Examples

import seraplot as sp
import random
cats   = ["Low", "Medium", "High"]
means  = [10, 50, 90]
values = [v for m in means for v in [random.gauss(m, 8) for _ in range(150)]]
chart = sp.build_ridgeline3d_chart(
    "Score Distribution by Group",
    categories=cats,
    values=values,
)
const sp = require('seraplot');
import random
const cats   = ["Low", "Medium", "High"]
const means  = [10, 50, 90]
const values = [v for m in means for v in [random.gauss(m, 8) for _ in range(150)]]
const chart = sp.build_ridgeline3d_chart("Score Distribution by Group",
cats,
{
    values: values
})
import * as sp from 'seraplot';
import random
const cats: string[] = ["Low", "Medium", "High"]
const means: number[] = [10, 50, 90]
const values: number[] = [v for m in means for v in [random.gauss(m, 8) for _ in range(150)]]
const chart = sp.build_ridgeline3d_chart("Score Distribution by Group",
cats,
{
    values: values
})
▶ Live Preview

Signature

sp.build_ridgeline3d_chart(
    title: str,
    categories: list[str],
    values: list[float],
    *,
    bandwidth: float = 1.0,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "Density",
) -> Chart

Aliases: sp.ridgeline3d


Description

Ridgeline 3D — surfaces KDE par catégorie arrangées le long de l'axe Y dans une scène WebGL.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
categorieslist[str]requisÉtiquettes des catégories
valueslist[float]requisDonnées concaténées en plat
bandwidthfloat1.0Bande passante KDE
palettelist[int] | NoneNoneCouleurs par ridge
bg_colorstr"#1a1a2e"Couleur de fond
widthint900Largeur du canvas
heightint600Hauteur du canvas
z_labelstr"Density"Étiquette de l'axe Z

Retourne

Chart


Exemples

import seraplot as sp
import random

cats   = ["Faible", "Moyen", "Haut"]
means  = [10, 50, 90]
values = [v for m in means for v in [random.gauss(m, 8) for _ in range(150)]]

chart = sp.build_ridgeline3d_chart(
    "Distribution des scores par groupe",
    categories=cats,
    values=values,
)

Bubble Chart 3D

Signature

sp.build_bubble3d_chart(
    title: str,
    x: list[float],
    y: list[float],
    z: list[float],
    sizes: list[float],
    *,
    color_labels: list[str] | None = None,
    color_values: list[float] | None = None,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "X",
    y_label: str = "Y",
    z_label: str = "Z",
    hover_json: str | None = None,
) -> Chart

Aliases: sp.bubble3d


Description

3D bubble chart — scatter in XYZ space where bubble radius encodes a fourth dimension.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
xlist[float]requiredX positions
ylist[float]requiredY positions
zlist[float]requiredZ positions
sizeslist[float]requiredBubble radii
color_labelslist[str] | NoneNoneCategorical color groups
color_valueslist[float] | NoneNoneContinuous colormap values
palettelist[int] | NoneNoneCustom color palette
bg_colorstr"#1a1a2e"Background color
widthint900Canvas width
heightint600Canvas height
hover_jsonstr | NoneNoneCustom hover JSON

Returns

Chart


Examples

import seraplot as sp
import random
n = 200
chart = sp.build_bubble3d_chart(
    "4D Dataset",
    x_values=[random.gauss(0,1) for _ in range(n)],
    y_values=[random.gauss(0,1) for _ in range(n)],
    z_values=[random.gauss(0,1) for _ in range(n)],
    size_values=[random.uniform(5, 30) for _ in range(n)],
    color_labels=[random.choice(["A","B","C"]) for _ in range(n)],
)
const sp = require('seraplot');
import random
const n = 200
const chart = sp.build_bubble3d_chart("4D Dataset",
[random.gauss(0,1) for _ in range(n)],
[random.gauss(0,1) for _ in range(n)],
[random.gauss(0,1) for _ in range(n)],
{
    size_values: [random.uniform(5, 30) for _ in range(n)],
    color_labels: [random.choice(["A","B","C"]) for _ in range(n)]
})
import * as sp from 'seraplot';
import random
const n: number = 200
const chart = sp.build_bubble3d_chart("4D Dataset",
[random.gauss(0,1) for _ in range(n)],
[random.gauss(0,1) for _ in range(n)],
[random.gauss(0,1) for _ in range(n)],
{
    size_values: [random.uniform(5, 30) for _ in range(n)],
    color_labels: [random.choice(["A","B","C"]) for _ in range(n)]
})
▶ Live Preview

Signature

sp.build_bubble3d_chart(
    title: str,
    x: list[float],
    y: list[float],
    z: list[float],
    sizes: list[float],
    *,
    color_labels: list[str] | None = None,
    color_values: list[float] | None = None,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "X",
    y_label: str = "Y",
    z_label: str = "Z",
    hover_json: str | None = None,
) -> Chart

Aliases: sp.bubble3d


Description

Graphique à bulles 3D — nuage de points XYZ où le rayon des bulles encode une quatrième dimension.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
xlist[float]requisPositions X
ylist[float]requisPositions Y
zlist[float]requisPositions Z
sizeslist[float]requisRayons des bulles
color_labelslist[str] | NoneNoneGroupes de couleur catégoriels
color_valueslist[float] | NoneNoneValeurs de colormap continues
palettelist[int] | NoneNonePalette de couleurs
bg_colorstr"#1a1a2e"Couleur de fond
widthint900Largeur du canvas
heightint600Hauteur du canvas
hover_jsonstr | NoneNoneJSON d'infobulle personnalisée

Retourne

Chart


Exemples

import seraplot as sp
import random

n = 200
chart = sp.build_bubble3d_chart(
    "Jeu de données 4D",
    x_values=[random.gauss(0,1) for _ in range(n)],
    y_values=[random.gauss(0,1) for _ in range(n)],
    z_values=[random.gauss(0,1) for _ in range(n)],
    size_values=[random.uniform(5, 30) for _ in range(n)],
    color_labels=[random.choice(["A","B","C"]) for _ in range(n)],
)

Pie Chart 3D

Signature

sp.build_pie3d_chart(
    title: str,
    labels: list[str],
    values: list[float],
    *,
    show_pct: bool = True,
    extrusion: float = 0.2,
    bg_color: str = "#1a1a2e",
    palette: list[int] | None = None,
    width: int = 700,
    height: int = 600,
    hover_json: str | None = None,
) -> Chart

Aliases: sp.pie3d


Description

3D pie chart rendered as extruded arc segments in a WebGL scene.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredSlice labels
valueslist[float]requiredSlice values
show_pctboolTrueShow percentage labels
extrusionfloat0.2Depth of pie extrusion
bg_colorstr"#1a1a2e"Background color
palettelist[int] | NoneNoneCustom palette
widthint700Canvas width
heightint600Canvas height
hover_jsonstr | NoneNoneCustom hover JSON

Returns

Chart


Examples

import seraplot as sp
chart = sp.build_pie3d_chart(
    "Market Share 3D",
    labels=["Chrome", "Safari", "Firefox", "Edge"],
    values=[65, 19, 4, 4],
)
const sp = require('seraplot');
const chart = sp.build_pie3d_chart("Market Share 3D",
["Chrome", "Safari", "Firefox", "Edge"],
{
    values: [65, 19, 4, 4]
})
import * as sp from 'seraplot';
const chart = sp.build_pie3d_chart("Market Share 3D",
["Chrome", "Safari", "Firefox", "Edge"],
{
    values: [65, 19, 4, 4]
})
▶ Live Preview

Signature

sp.build_pie3d_chart(
    title: str,
    labels: list[str],
    values: list[float],
    *,
    show_pct: bool = True,
    extrusion: float = 0.2,
    bg_color: str = "#1a1a2e",
    palette: list[int] | None = None,
    width: int = 700,
    height: int = 600,
    hover_json: str | None = None,
) -> Chart

Aliases: sp.pie3d


Description

Camembert 3D rendu comme des segments d'arc extrudés dans une scène WebGL.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
labelslist[str]requisÉtiquettes des parts
valueslist[float]requisValeurs des parts
show_pctboolTrueAfficher les pourcentages
extrusionfloat0.2Profondeur d'extrusion
bg_colorstr"#1a1a2e"Couleur de fond
palettelist[int] | NoneNonePalette personnalisée
widthint700Largeur du canvas
heightint600Hauteur du canvas
hover_jsonstr | NoneNoneJSON d'infobulle personnalisée

Retourne

Chart


Exemples

import seraplot as sp

chart = sp.build_pie3d_chart(
    "Parts de marché 3D",
    labels=["Chrome", "Safari", "Firefox", "Edge"],
    values=[65, 19, 4, 4],
)

Violin Chart 3D

Signature

sp.build_violin3d_chart(
    title: str,
    categories: list[str],
    values: list[float],
    *,
    bandwidth: float = 1.0,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "Density",
) -> Chart

Aliases: sp.violin3d


Description

3D violin chart — KDE-based distribution surfaces per category rendered in WebGL.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
categorieslist[str]requiredCategory labels
valueslist[float]requiredFlat sample data (equal count per category)
bandwidthfloat1.0KDE bandwidth
palettelist[int] | NoneNonePer-category colors
bg_colorstr"#1a1a2e"Background color
widthint900Canvas width
heightint600Canvas height

Returns

Chart


Examples

import seraplot as sp
import random
groups = ["Control", "Treatment A", "Treatment B"]
means  = [50, 65, 72]
values = [v for m in means for v in [random.gauss(m, 8) for _ in range(80)]]
chart = sp.build_violin3d_chart(
    "Trial Results",
    categories=groups,
    values=values,
)
const sp = require('seraplot');
import random
const groups = ["Control", "Treatment A", "Treatment B"]
const means  = [50, 65, 72]
const values = [v for m in means for v in [random.gauss(m, 8) for _ in range(80)]]
const chart = sp.build_violin3d_chart("Trial Results",
{
    categories: groups,
    values: values
})
import * as sp from 'seraplot';
import random
const groups: string[] = ["Control", "Treatment A", "Treatment B"]
const means: number[] = [50, 65, 72]
const values: number[] = [v for m in means for v in [random.gauss(m, 8) for _ in range(80)]]
const chart = sp.build_violin3d_chart("Trial Results",
{
    categories: groups,
    values: values
})
▶ Live Preview

Signature

sp.build_violin3d_chart(
    title: str,
    categories: list[str],
    values: list[float],
    *,
    bandwidth: float = 1.0,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "Density",
) -> Chart

Aliases: sp.violin3d


Description

Graphique en violon 3D — surfaces de distribution basées sur KDE par catégorie rendues en WebGL.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
categorieslist[str]requisÉtiquettes des catégories
valueslist[float]requisDonnées échantillon plates (nombre égal par catégorie)
bandwidthfloat1.0Bande passante KDE
palettelist[int] | NoneNoneCouleurs par catégorie
bg_colorstr"#1a1a2e"Couleur de fond
widthint900Largeur du canvas
heightint600Hauteur du canvas

Retourne

Chart


Exemples

import seraplot as sp
import random

groupes = ["Contrôle", "Traitement A", "Traitement B"]
means  = [50, 65, 72]
values = [v for m in means for v in [random.gauss(m, 8) for _ in range(80)]]

chart = sp.build_violin3d_chart(
    "Résultats de l'essai",
    categories=groupes,
    values=values,
)

Heatmap 3D

Signature

sp.build_heatmap3d_chart(
    title: str,
    labels: list[str],
    flat_matrix: list[float],
    *,
    col_labels: list[str] | None = None,
    color_low: int = 0,
    color_high: int = 0,
    extrusion_scale: float = 1.0,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "",
) -> Chart

Aliases: sp.heatmap3d


Description

3D heatmap where cell values are extruded as bars rising from a flat grid. Higher values produce taller columns.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredRow labels
flat_matrixlist[float]requiredMatrix values, row-major
col_labelslist[str] | NoneNoneColumn labels
color_lowintautoLow value color
color_highintautoHigh value color
extrusion_scalefloat1.0Height multiplier for bars
bg_colorstr"#1a1a2e"Background color
widthint900Canvas width
heightint600Canvas height

Returns

Chart


Examples

import seraplot as sp
features = ["A", "B", "C", "D"]
n = len(features)
matrix = [[abs(i - j) * 0.25 for j in range(n)] for i in range(n)]
chart = sp.build_heatmap3d_chart(
    "Distance Matrix 3D",
    x_labels=features,
    y_labels=features,
    values=matrix,
)
const sp = require('seraplot');
const features = ["A", "B", "C", "D"]
const n = len(features)
const matrix = [[abs(i - j) * 0.25 for j in range(n)] for i in range(n)]
const chart = sp.build_heatmap3d_chart("Distance Matrix 3D",
features,
features,
{
    values: matrix
})
import * as sp from 'seraplot';
const features: string[] = ["A", "B", "C", "D"]
const n = len(features)
const matrix: number[] = [[abs(i - j) * 0.25 for j in range(n)] for i in range(n)]
const chart = sp.build_heatmap3d_chart("Distance Matrix 3D",
features,
features,
{
    values: matrix
})
▶ Live Preview

Signature

sp.build_heatmap3d_chart(
    title: str,
    labels: list[str],
    flat_matrix: list[float],
    *,
    col_labels: list[str] | None = None,
    color_low: int = 0,
    color_high: int = 0,
    extrusion_scale: float = 1.0,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "",
) -> Chart

Aliases: sp.heatmap3d


Description

Heatmap 3D où les valeurs sont extrudées comme des barres s'élevant d'une grille plate. Les valeurs plus hautes produisent des colonnes plus élevées.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
labelslist[str]requisÉtiquettes des lignes
flat_matrixlist[float]requisValeurs de la matrice, en ligne-major
col_labelslist[str] | NoneNoneÉtiquettes de colonnes
color_lowintautoCouleur pour les valeurs basses
color_highintautoCouleur pour les valeurs hautes
extrusion_scalefloat1.0Multiplicateur de hauteur des barres
bg_colorstr"#1a1a2e"Couleur de fond
widthint900Largeur du canvas
heightint600Hauteur du canvas

Retourne

Chart


Exemples

import seraplot as sp

features = ["A", "B", "C", "D"]
n = len(features)
matrice = [[abs(i - j) * 0.25 for j in range(n)] for i in range(n)]
flat = [v for row in matrice for v in row]

chart = sp.build_heatmap3d_chart(
    "Matrice de distance 3D",
    labels=features,
    flat_matrix=flat,
    col_labels=features,
)

Candlestick Chart 3D

Signature

sp.build_candlestick3d_chart(
    title: str,
    dates: list[str],
    opens: list[float],
    highs: list[float],
    lows: list[float],
    closes: list[float],
    *,
    color_up: int = 0x22c55e,
    color_down: int = 0xef4444,
    bg_color: str = "#1a1a2e",
    width: int = 1000,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "",
    hover_json: str | None = None,
) -> Chart

Aliases: sp.candlestick3d


Description

OHLC candlestick chart rendered in 3D WebGL. Candles are extruded as 3D prisms.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
dateslist[str]requiredDate labels
openslist[float]requiredOpen prices
highslist[float]requiredHigh prices
lowslist[float]requiredLow prices
closeslist[float]requiredClose prices
color_upint0x22c55eBullish candle color
color_downint0xef4444Bearish candle color
bg_colorstr"#1a1a2e"Background
widthint1000Canvas width
heightint600Canvas height

Returns

Chart


Examples

import seraplot as sp
chart = sp.build_candlestick3d_chart(
    "BTC/USD 3D",
    labels=["Mon", "Tue", "Wed", "Thu", "Fri"],
    open= [42000, 43500, 41800, 44000, 45200],
    high= [44000, 44200, 43500, 46000, 47000],
    low=  [41500, 43000, 40000, 43500, 44800],
    close=[43500, 41800, 44000, 45200, 46500],
)
const sp = require('seraplot');
const chart = sp.build_candlestick3d_chart("BTC/USD 3D",
["Mon", "Tue", "Wed", "Thu", "Fri"],
[42000, 43500, 41800, 44000, 45200],
[44000, 44200, 43500, 46000, 47000],
[41500, 43000, 40000, 43500, 44800],
{
    close: [43500, 41800, 44000, 45200, 46500]
})
import * as sp from 'seraplot';
const chart = sp.build_candlestick3d_chart("BTC/USD 3D",
["Mon", "Tue", "Wed", "Thu", "Fri"],
[42000, 43500, 41800, 44000, 45200],
[44000, 44200, 43500, 46000, 47000],
[41500, 43000, 40000, 43500, 44800],
{
    close: [43500, 41800, 44000, 45200, 46500]
})
▶ Live Preview

Signature

sp.build_candlestick3d_chart(
    title: str,
    dates: list[str],
    opens: list[float],
    highs: list[float],
    lows: list[float],
    closes: list[float],
    *,
    color_up: int = 0x22c55e,
    color_down: int = 0xef4444,
    bg_color: str = "#1a1a2e",
    width: int = 1000,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "",
    hover_json: str | None = None,
) -> Chart

Aliases: sp.candlestick3d


Description

Graphique bougie OHLC rendu en WebGL 3D. Les bougies sont extrudées comme des prismes 3D.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
dateslist[str]requisÉtiquettes de dates
openslist[float]requisPrix d'ouverture
highslist[float]requisPrix hauts
lowslist[float]requisPrix bas
closeslist[float]requisPrix de clôture
color_upint0x22c55eCouleur des bougies haussières
color_downint0xef4444Couleur des bougies baissières
bg_colorstr"#1a1a2e"Couleur de fond
widthint1000Largeur du canvas
heightint600Hauteur du canvas

Retourne

Chart


Exemples

import seraplot as sp

chart = sp.build_candlestick3d_chart(
    "BTC/USD 3D",
    labels=["Lun", "Mar", "Mer", "Jeu", "Ven"],
    open= [42000, 43500, 41800, 44000, 45200],
    high= [44000, 44200, 43500, 46000, 47000],
    low=  [41500, 43000, 40000, 43500, 44800],
    close=[43500, 41800, 44000, 45200, 46500],
)

Dumbbell Chart 3D

Signature

sp.build_dumbbell3d_chart(
    title: str,
    labels: list[str],
    values_start: list[float],
    values_end: list[float],
    *,
    color_start: int = 0x6366f1,
    color_end: int = 0xf43f5e,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "",
    show_text: bool = False,
) -> Chart

Aliases: sp.dumbbell3d


Description

Dumbbell chart in 3D — connects start and end spheres with a 3D tube.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredCategory labels
values_startlist[float]requiredStart values
values_endlist[float]requiredEnd values
color_startint0x6366f1Start sphere color
color_endint0xf43f5eEnd sphere color
bg_colorstr"#1a1a2e"Background
widthint900Canvas width
heightint600Canvas height
show_textboolFalseShow value labels

Returns

Chart


Examples

import seraplot as sp
chart = sp.build_dumbbell3d_chart(
    "Before vs After 3D",
    labels=["Group A", "Group B", "Group C"],
    values_start=[40, 55, 70],
    values_end=[60, 75, 85],
)
const sp = require('seraplot');
const chart = sp.build_dumbbell3d_chart("Before vs After 3D",
["Group A", "Group B", "Group C"],
[40, 55, 70],
{
    values_end: [60, 75, 85]
})
import * as sp from 'seraplot';
const chart = sp.build_dumbbell3d_chart("Before vs After 3D",
["Group A", "Group B", "Group C"],
[40, 55, 70],
{
    values_end: [60, 75, 85]
})
▶ Live Preview

Signature

sp.build_dumbbell3d_chart(
    title: str,
    labels: list[str],
    values_start: list[float],
    values_end: list[float],
    *,
    color_start: int = 0x6366f1,
    color_end: int = 0xf43f5e,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "",
    show_text: bool = False,
) -> Chart

Aliases: sp.dumbbell3d


Description

Graphique haltère 3D — connecte les sphères de début et de fin avec un tube 3D.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
labelslist[str]requisÉtiquettes des catégories
values_startlist[float]requisValeurs de départ
values_endlist[float]requisValeurs d'arrivée
color_startint0x6366f1Couleur de la sphère de départ
color_endint0xf43f5eCouleur de la sphère d'arrivée
bg_colorstr"#1a1a2e"Couleur de fond
widthint900Largeur du canvas
heightint600Hauteur du canvas
show_textboolFalseAfficher les étiquettes de valeur

Retourne

Chart


Exemples

import seraplot as sp

chart = sp.build_dumbbell3d_chart(
    "Avant vs Après 3D",
    labels=["Groupe A", "Groupe B", "Groupe C"],
    values_start=[40, 55, 70],
    values_end=[60, 75, 85],
)

Funnel Chart 3D

Signature

sp.build_funnel3d_chart(
    title: str,
    labels: list[str],
    values: list[float],
    *,
    show_text: bool = True,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 700,
    height: int = 600,
    hover_json: str | None = None,
) -> Chart

Aliases: sp.funnel3d


Description

3D funnel chart where each stage is a truncated cone (frustum) in a WebGL scene.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredStage labels
valueslist[float]requiredStage values
show_textboolTrueShow value labels
palettelist[int] | NoneNonePer-stage colors
bg_colorstr"#1a1a2e"Background
widthint700Canvas width
heightint600Canvas height
hover_jsonstr | NoneNoneCustom hover JSON

Returns

Chart


Examples

import seraplot as sp
chart = sp.build_funnel3d_chart(
    "Conversion Funnel 3D",
    labels=["Visitors", "Leads", "Opportunities", "Proposals", "Won"],
    values=[10000, 3200, 1100, 450, 120],
)
const sp = require('seraplot');
const chart = sp.build_funnel3d_chart("Conversion Funnel 3D",
["Visitors", "Leads", "Opportunities", "Proposals", "Won"],
{
    values: [10000, 3200, 1100, 450, 120]
})
import * as sp from 'seraplot';
const chart = sp.build_funnel3d_chart("Conversion Funnel 3D",
["Visitors", "Leads", "Opportunities", "Proposals", "Won"],
{
    values: [10000, 3200, 1100, 450, 120]
})
▶ Live Preview

Signature

sp.build_funnel3d_chart(
    title: str,
    labels: list[str],
    values: list[float],
    *,
    show_text: bool = True,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 700,
    height: int = 600,
    hover_json: str | None = None,
) -> Chart

Aliases: sp.funnel3d


Description

Entonnoir 3D où chaque étape est un cône tronqué (frustum) dans une scène WebGL.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
labelslist[str]requisÉtiquettes des étapes
valueslist[float]requisValeurs des étapes
show_textboolTrueAfficher les étiquettes de valeur
palettelist[int] | NoneNoneCouleurs par étape
bg_colorstr"#1a1a2e"Couleur de fond
widthint700Largeur du canvas
heightint600Hauteur du canvas
hover_jsonstr | NoneNoneJSON d'infobulle personnalisée

Retourne

Chart


Exemples

import seraplot as sp

chart = sp.build_funnel3d_chart(
    "Entonnoir de conversion 3D",
    labels=["Visiteurs", "Prospects", "Opportunités", "Propositions", "Conclus"],
    values=[10000, 3200, 1100, 450, 120],
)

Sunburst Chart 3D

Signature

sp.build_sunburst3d_chart(
    title: str,
    labels: list[str],
    parents: list[str],
    values: list[float],
    *,
    extrusion: float = 0.15,
    bg_color: str = "#1a1a2e",
    palette: list[int] | None = None,
    width: int = 700,
    height: int = 600,
    hover_json: str | None = None,
) -> Chart

Aliases: sp.sunburst3d


Description

3D sunburst chart — concentric extruded arc rings in a WebGL scene.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredNode labels
parentslist[str]requiredParent labels
valueslist[float]requiredNode sizes
extrusionfloat0.15Depth of arc extrusion
bg_colorstr"#1a1a2e"Background
palettelist[int] | NoneNoneCustom palette
widthint700Canvas width
heightint600Canvas height
hover_jsonstr | NoneNoneCustom hover JSON

Returns

Chart


Examples

import seraplot as sp
labels  = ["Root", "A", "B", "A1", "A2", "B1"]
parents = ["", "Root", "Root", "A", "A", "B"]
values  = [1, 40, 60, 25, 15, 60]
chart = sp.build_sunburst3d_chart(
    "Org Chart 3D",
    labels=labels, parents=parents, values=values,
)
const sp = require('seraplot');
const labels  = ["Root", "A", "B", "A1", "A2", "B1"]
const parents = ["", "Root", "Root", "A", "A", "B"]
const values  = [1, 40, 60, 25, 15, 60]
const chart = sp.build_sunburst3d_chart("Org Chart 3D",
labels,
parents,
{
    values: values
})
import * as sp from 'seraplot';
const labels: string[] = ["Root", "A", "B", "A1", "A2", "B1"]
const parents: string[] = ["", "Root", "Root", "A", "A", "B"]
const values: number[] = [1, 40, 60, 25, 15, 60]
const chart = sp.build_sunburst3d_chart("Org Chart 3D",
labels,
parents,
{
    values: values
})
▶ Live Preview

Signature

sp.build_sunburst3d_chart(
    title: str,
    labels: list[str],
    parents: list[str],
    values: list[float],
    *,
    extrusion: float = 0.15,
    bg_color: str = "#1a1a2e",
    palette: list[int] | None = None,
    width: int = 700,
    height: int = 600,
    hover_json: str | None = None,
) -> Chart

Aliases: sp.sunburst3d


Description

Sunburst 3D — anneaux d'arc extrudés concentriques dans une scène WebGL.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
labelslist[str]requisÉtiquettes des nœuds
parentslist[str]requisÉtiquettes des parents
valueslist[float]requisTailles des nœuds
extrusionfloat0.15Profondeur d'extrusion des arcs
bg_colorstr"#1a1a2e"Couleur de fond
palettelist[int] | NoneNonePalette personnalisée
widthint700Largeur du canvas
heightint600Hauteur du canvas
hover_jsonstr | NoneNoneJSON d'infobulle personnalisée

Retourne

Chart


Exemples

import seraplot as sp

labels  = ["Racine", "A", "B", "A1", "A2", "B1"]
parents = ["", "Racine", "Racine", "A", "A", "B"]
values  = [1, 40, 60, 25, 15, 60]

chart = sp.build_sunburst3d_chart(
    "Organigramme 3D",
    labels=labels, parents=parents, values=values,
)

Stacked Bar Chart 3D

Signature

sp.build_stacked_bar3d_chart(
    title: str,
    category_labels: list[str],
    series_values: list[float],
    *,
    series_names: list[str] | None = None,
    show_values: bool = False,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "",
) -> Chart

Aliases: sp.stacked_bar3d


Description

3D stacked bar chart — each bar is segmented into series, rendered as stacked prisms.

series_values is a flat list in row-major order: [cat0_s0, cat0_s1, …, cat1_s0, …].


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
category_labelslist[str]requiredCategory labels
series_valueslist[float]requiredFlat row-major series data
series_nameslist[str] | NoneNoneLegend names
show_valuesboolFalseLabels on segments
palettelist[int] | NoneNonePer-series colors
bg_colorstr"#1a1a2e"Background
widthint900Canvas width
heightint600Canvas height

Returns

Chart


Examples

import seraplot as sp
categories = ["Q1", "Q2", "Q3", "Q4"]
series_data = [
    [30, 40, 25, 50],
    [20, 35, 45, 30],
    [50, 25, 30, 20],
]
chart = sp.build_stacked_bar3d_chart(
    "Quarterly Revenue 3D",
    category_labels=categories,
    series_values=series_data,
    series_names=["Product A", "Product B", "Product C"],
)
const sp = require('seraplot');
const categories = ["Q1", "Q2", "Q3", "Q4"]
const series_data = [
    [30, 40, 25, 50],
    [20, 35, 45, 30],
    [50, 25, 30, 20],
]
const chart = sp.build_stacked_bar3d_chart("Quarterly Revenue 3D",
categories,
{
    series_values: series_data,
    series_names: ["Product A", "Product B", "Product C"]
})
import * as sp from 'seraplot';
const categories: string[] = ["Q1", "Q2", "Q3", "Q4"]
const series_data: number[] = [
    [30, 40, 25, 50],
    [20, 35, 45, 30],
    [50, 25, 30, 20],
]
const chart = sp.build_stacked_bar3d_chart("Quarterly Revenue 3D",
categories,
{
    series_values: series_data,
    series_names: ["Product A", "Product B", "Product C"]
})
▶ Live Preview

Signature

sp.build_stacked_bar3d_chart(
    title: str,
    category_labels: list[str],
    series_values: list[float],
    *,
    series_names: list[str] | None = None,
    show_values: bool = False,
    palette: list[int] | None = None,
    bg_color: str = "#1a1a2e",
    width: int = 900,
    height: int = 600,
    x_label: str = "",
    y_label: str = "",
    z_label: str = "",
) -> Chart

Aliases: sp.stacked_bar3d


Description

Graphique en barres empilées 3D — chaque barre est segmentée en séries, rendues comme des prismes empilés.

series_values est une liste plate en ordre ligne-major : [cat0_s0, cat0_s1, …, cat1_s0, …].


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
category_labelslist[str]requisÉtiquettes des catégories
series_valueslist[float]requisDonnées en ligne-major
series_nameslist[str] | NoneNoneNoms de légende
show_valuesboolFalseÉtiquettes sur les segments
palettelist[int] | NoneNoneCouleurs par série
bg_colorstr"#1a1a2e"Couleur de fond
widthint900Largeur du canvas
heightint600Hauteur du canvas

Retourne

Chart


Exemples

import seraplot as sp

categories = ["T1", "T2", "T3", "T4"]
données = [
    [30, 40, 25, 50],
    [20, 35, 45, 30],
    [50, 25, 30, 20],
]

chart = sp.build_stacked_bar3d_chart(
    "Revenus trimestriels 3D",
    category_labels=categories,
    series_values=données,
    series_names=["Produit A", "Produit B", "Produit C"],
)

Globe 3D

Signature

sp.build_globe3d_chart(
    title: str,
    labels: list[str],
    latitudes: list[float],
    longitudes: list[float],
    values: list[float],
    *,
    color_hex: int = 0x6366F1,
    palette: list[int] | None = None,
    bg_color: str = "#0f172a",
    width: int = 900,
    height: int = 700,
    hover_json: str | None = None,
    bar_height_scale: float = 1.0,
    show_graticule: bool = True,
) -> Chart

Aliases: sp.globe3d


Description

Interactive 3D globe — geo data plotted as vertical bars or spikes on a sphere. Drag to rotate, scroll to zoom.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredLocation names
latitudeslist[float]requiredDecimal latitudes
longitudeslist[float]requiredDecimal longitudes
valueslist[float]requiredBar heights per location
color_hexint0x6366F1Default bar color
palettelist[int] | NoneNoneCustom palette
bg_colorstr"#0f172a"Background color
widthint900Canvas width
heightint700Canvas height
bar_height_scalefloat1.0Global height multiplier
show_graticuleboolTrueDraw lat/lon grid lines
hover_jsonstr | NoneNoneCustom hover JSON

Returns

Chart


Examples

World population

import seraplot as sp
chart = sp.build_globe3d_chart(
    "World Population Spikes",
    labels=["China", "India", "USA", "Brazil", "Nigeria"],
    latitudes=[35.86, 20.59, 37.09, -14.23, 9.08],
    longitudes=[104.19, 78.96, -95.71, -51.92, 8.67],
    values=[1412, 1380, 331, 212, 218],
)
const sp = require('seraplot');
const chart = sp.build_globe3d_chart("World Population Spikes",
["China", "India", "USA", "Brazil", "Nigeria"],
[35.86, 20.59, 37.09, -14.23, 9.08],
{
    longitudes: [104.19, 78.96, -95.71, -51.92, 8.67],
    values: [1412, 1380, 331, 212, 218]
})
import * as sp from 'seraplot';
const chart = sp.build_globe3d_chart("World Population Spikes",
["China", "India", "USA", "Brazil", "Nigeria"],
[35.86, 20.59, 37.09, -14.23, 9.08],
{
    longitudes: [104.19, 78.96, -95.71, -51.92, 8.67],
    values: [1412, 1380, 331, 212, 218]
})
▶ Live Preview

Signature

sp.build_globe3d_chart(
    title: str,
    labels: list[str],
    latitudes: list[float],
    longitudes: list[float],
    values: list[float],
    *,
    color_hex: int = 0x6366F1,
    palette: list[int] | None = None,
    bg_color: str = "#0f172a",
    width: int = 900,
    height: int = 700,
    hover_json: str | None = None,
    bar_height_scale: float = 1.0,
    show_graticule: bool = True,
) -> Chart

Aliases: sp.globe3d


Description

Globe interactif 3D — données géographiques tracées comme des barres verticales sur une sphère. Faites glisser pour tourner, défilez pour zoomer.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
labelslist[str]requisNoms des lieux
latitudeslist[float]requisLatitudes décimales
longitudeslist[float]requisLongitudes décimales
valueslist[float]requisHauteurs des barres par lieu
color_hexint0x6366F1Couleur par défaut des barres
palettelist[int] | NoneNonePalette personnalisée
bg_colorstr"#0f172a"Couleur de fond
widthint900Largeur du canvas
heightint700Hauteur du canvas
bar_height_scalefloat1.0Multiplicateur global de hauteur
show_graticuleboolTrueDessiner les lignes de latitude/longitude
hover_jsonstr | NoneNoneJSON d'infobulle personnalisée

Retourne

Chart


Exemples

import seraplot as sp

chart = sp.build_globe3d_chart(
    "Population mondiale",
    labels=["Chine", "Inde", "USA", "Brésil", "Nigéria"],
    latitudes=[35.86, 20.59, 37.09, -14.23, 9.08],
    longitudes=[104.19, 78.96, -95.71, -51.92, 8.67],
    values=[1412, 1380, 331, 212, 218],
)

Map Charts

SeraPlot provides geographic chart types for visualizing spatial data on world maps.

ChartFunction
Bubble Mapbubble_map()
Choroplethchoropleth()

SeraPlot propose des types de graphiques géographiques pour visualiser des données spatiales sur des cartes mondiales.

GraphiqueFonction
Carte à bullesbubble_map()
Choroplethchoropleth()

Bubble Map

Signature

sp.build_bubble_map(
    title: str,
    labels: list[str],
    values: list[float],
    *,
    latitudes: list[float] | None = None,
    longitudes: list[float] | None = None,
    iso_codes: list[str] | None = None,
    color_hex: int = 0x6366F1,
    palette: list[int] | None = None,
    width: int = 1000,
    height: int = 600,
    background: str | None = None,
    hover_json: str | None = None,
    bubble_opacity: float = 0.6,
    min_bubble_size: float = 5.0,
    max_bubble_size: float = 50.0,
) -> Chart

Aliases: sp.bubble_map


Description

World map with proportional bubbles at geographic coordinates. Use iso_codes for country-level data (the library resolves centroids automatically), or pass explicit latitudes / longitudes.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredLocation names
valueslist[float]requiredBubble sizes
latitudeslist[float] | NoneNoneManual latitudes
longitudeslist[float] | NoneNoneManual longitudes
iso_codeslist[str] | NoneNoneISO-3166 alpha-3 country codes
color_hexint0x6366F1Bubble color
palettelist[int] | NoneNoneMulti-group palette
widthint1000Canvas width
heightint600Canvas height
bubble_opacityfloat0.6Bubble transparency (0–1)
min_bubble_sizefloat5.0Minimum bubble radius in pixels
max_bubble_sizefloat50.0Maximum bubble radius in pixels
hover_jsonstr | NoneNoneCustom hover JSON

Returns

Chart


Examples

GDP per country (ISO code lookup)

import seraplot as sp
chart = sp.build_bubble_map(
    "GDP by Country",
    labels=["USA", "CHN", "DEU", "JPN", "FRA"],
    values=[25500, 17700, 4400, 4200, 3100],
)
const sp = require('seraplot');
const chart = sp.build_bubble_map("GDP by Country",
["USA", "CHN", "DEU", "JPN", "FRA"],
{
    values: [25500, 17700, 4400, 4200, 3100]
})
import * as sp from 'seraplot';
const chart = sp.build_bubble_map("GDP by Country",
["USA", "CHN", "DEU", "JPN", "FRA"],
{
    values: [25500, 17700, 4400, 4200, 3100]
})
▶ Live Preview

Custom coordinates

import seraplot as sp

chart = sp.build_bubble_map(
    "City Populations",
    labels=["Paris", "Tokyo", "New York", "Lagos"],
    values=[11, 37, 20, 15],
    latitudes=[48.85, 35.68, 40.71, 6.52],
    longitudes=[2.35, 139.69, -74.01, 3.38],
)

Signature

sp.build_bubble_map(
    title: str,
    labels: list[str],
    values: list[float],
    *,
    latitudes: list[float] | None = None,
    longitudes: list[float] | None = None,
    iso_codes: list[str] | None = None,
    color_hex: int = 0x6366F1,
    palette: list[int] | None = None,
    width: int = 1000,
    height: int = 600,
    background: str | None = None,
    hover_json: str | None = None,
    bubble_opacity: float = 0.6,
    min_bubble_size: float = 5.0,
    max_bubble_size: float = 50.0,
) -> Chart

Aliases: sp.bubble_map


Description

Carte mondiale avec des bulles proportionnelles aux coordonnées géographiques. Utilisez iso_codes pour les données par pays (la bibliothèque résout les centroïdes automatiquement), ou passez des latitudes / longitudes explicites.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
labelslist[str]requisNoms des lieux
valueslist[float]requisTailles des bulles
latitudeslist[float] | NoneNoneLatitudes manuelles
longitudeslist[float] | NoneNoneLongitudes manuelles
iso_codeslist[str] | NoneNoneCodes ISO-3166 alpha-3 des pays
color_hexint0x6366F1Couleur des bulles
palettelist[int] | NoneNonePalette multi-groupes
widthint1000Largeur du canvas
heightint600Hauteur du canvas
bubble_opacityfloat0.6Transparence des bulles (0–1)
min_bubble_sizefloat5.0Rayon minimal des bulles en pixels
max_bubble_sizefloat50.0Rayon maximal des bulles en pixels
hover_jsonstr | NoneNoneJSON d'infobulle personnalisée

Retourne

Chart


Exemples

import seraplot as sp

chart = sp.build_bubble_map(
    "PIB par pays",
    labels=["USA", "CHN", "DEU", "JPN", "FRA"],
    values=[25500, 17700, 4400, 4200, 3100],
)
import seraplot as sp

chart = sp.build_bubble_map(
    "Populations urbaines",
    labels=["Paris", "Tokyo", "New York", "Lagos"],
    values=[11, 37, 20, 15],
    latitudes=[48.85, 35.68, 40.71, 6.52],
    longitudes=[2.35, 139.69, -74.01, 3.38],
)

Choropleth Map

Signature

sp.build_choropleth(
    title: str,
    labels: list[str],
    values: list[float],
    *,
    iso_codes: list[str] | None = None,
    color_low: int = 0,
    color_high: int = 0,
    palette: list[int] | None = None,
    width: int = 1000,
    height: int = 600,
    background: str | None = None,
    hover_json: str | None = None,
    show_legend: bool = True,
    null_color: int = 0xdddddd,
) -> Chart

Aliases: sp.choropleth


Description

Choropleth (filled map) — country or region polygons colored by a scalar value.

Countries without data receive the null_color. Provide iso_codes (ISO-3166 alpha-3) to match countries automatically.


Parameters

ParameterTypeDefaultDescription
titlestrrequiredChart title
labelslist[str]requiredCountry
valueslist[float]requiredValues to color by
iso_codeslist[str] | NoneNoneISO-3166 alpha-3 codes
color_lowintautoLow value color
color_highintautoHigh value color
null_colorint0xddddddColor for countries with no data
widthint1000Canvas width
heightint600Canvas height
show_legendboolTrueShow color scale legend
hover_jsonstr | NoneNoneCustom hover JSON

Returns

Chart


Examples

Unemployment rate choropleth

import seraplot as sp
chart = sp.build_choropleth(
    "Unemployment Rate by Country",
    labels=["FRA", "DEU", "ESP", "ITA", "PRT"],
    values=[7.1, 3.0, 11.8, 6.7, 6.2],
)
const sp = require('seraplot');
const chart = sp.build_choropleth("Unemployment Rate by Country",
["FRA", "DEU", "ESP", "ITA", "PRT"],
{
    values: [7.1, 3.0, 11.8, 6.7, 6.2]
})
import * as sp from 'seraplot';
const chart = sp.build_choropleth("Unemployment Rate by Country",
["FRA", "DEU", "ESP", "ITA", "PRT"],
{
    values: [7.1, 3.0, 11.8, 6.7, 6.2]
})
▶ Live Preview

Signature

sp.build_choropleth(
    title: str,
    labels: list[str],
    values: list[float],
    *,
    iso_codes: list[str] | None = None,
    color_low: int = 0,
    color_high: int = 0,
    palette: list[int] | None = None,
    width: int = 1000,
    height: int = 600,
    background: str | None = None,
    hover_json: str | None = None,
    show_legend: bool = True,
    null_color: int = 0xdddddd,
) -> Chart

Aliases: sp.choropleth


Description

Carte choro-plèthe — polygones de pays/régions colorés par une valeur scalaire. Les pays sans données reçoivent la null_color. Fournissez des iso_codes (ISO-3166 alpha-3) pour associer les pays automatiquement.


Paramètres

ParamètreTypeDéfautDescription
titlestrrequisTitre du graphique
labelslist[str]requisPays
valueslist[float]requisValeurs pour la colorisation
iso_codeslist[str] | NoneNoneCodes ISO-3166 alpha-3
color_lowintautoCouleur pour les valeurs basses
color_highintautoCouleur pour les valeurs hautes
null_colorint0xddddddCouleur des pays sans données
widthint1000Largeur du canvas
heightint600Hauteur du canvas
show_legendboolTrueAfficher l'échelle de couleur
hover_jsonstr | NoneNoneJSON d'infobulle personnalisée

Retourne

Chart


Exemples

import seraplot as sp

chart = sp.build_choropleth(
    "Taux de chômage par pays",
    labels=["FRA", "DEU", "ESP", "ITA", "PRT"],
    values=[7.1, 3.0, 11.8, 6.7, 6.2],
)

SeraML — Machine Learning

All models are sklearn-compatible. Swap the import, keep the code.

📈 Linear

🌲 Tree-Based

🔍 Neighbors

📊 Naive Bayes

⚡ SVM

🔬 Decomposition

🔮 Clustering

🔧 Preprocessing

🚨 Anomaly Detection

⚙️ Model Selection

📦 Registry

  • SaveModel — Save model to the in-memory registry with name, version, and metadata.

📏 Metrics

  • MetricScore — Compute a named metric score (accuracy, r2, f1, etc.) from predictions.

Clustering

EN — Density-based and centroid-based clustering algorithms.

FR — Algorithmes de clustering basés sur la densité et les centroïdes.

Contents

KmeansFitPredict

Clusterer sklearn-compatible 🔮 Clustering

K-Means — Lloyd's algorithm with k-means++ initialisation. / K-Means — algorithme de Lloyd avec initialisation k-means++.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=500, centers=4)
result = sp.KMeans(k=4, max_iter=300).fit_predict(X)
print(result)
💡
EN — Drop-in replacement: sp.KmeansFitPredict has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_kmeans_fit_predict — aliases: kmeans_fit_predict, ml_kmeans

Python class
sp.KmeansFitPredict(k=3, max_iter=300, n_init=10)
Constructor Parameters
ParameterTypeDefaultDescription
kint3Number of clusters.
max_iterint300Maximum iterations.
n_initint10Number of random restarts.
Returns

JSON with labels, inertia.

Algorithm

$$J = \sum_{k=1}^{K}\sum_{i \in C_k}|x_i - \mu_k|_2^2$$

Example
import seraplot as sp, numpy as np
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=500, centers=4)
result = sp.KMeans(k=4, max_iter=300).fit_predict(X)
print(result)

Référence API

Nom de fonction JSON

ml_kmeans_fit_predict — alias : kmeans_fit_predict, ml_kmeans

Classe Python
sp.KmeansFitPredict(k=3, max_iter=300, n_init=10)
Paramètres du constructeur
ParamètreTypeDéfautDescription
kint3Nombre de clusters.
max_iterint300Nombre maximum d'itérations.
n_initint10Nombre de redémarrages aléatoires.
Retourne

JSON avec labels, inertia.

Algorithme

$$J = \sum_{k=1}^{K}\sum_{i \in C_k}|x_i - \mu_k|_2^2$$

Exemple
import seraplot as sp, numpy as np
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=500, centers=4)
result = sp.KMeans(k=4, max_iter=300).fit_predict(X)
print(result)

DbscanFitPredict

Clusterer sklearn-compatible 🔮 Clustering

DBSCAN — density-based spatial clustering, no preset number of clusters. / DBSCAN — clustering spatial basé sur la densité, sans nombre de clusters prédéfini.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.6)
result = sp.DBSCAN(eps=0.8, min_samples=5).fit_predict(X)
print(result)
💡
EN — Drop-in replacement: sp.DbscanFitPredict has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_dbscan_fit_predict — aliases: dbscan_fit_predict, ml_dbscan

Python class
sp.DbscanFitPredict(eps=0.5, min_samples=5)
Constructor Parameters
ParameterTypeDefaultDescription
epsfloat0.5Neighbourhood radius.
min_samplesint5Minimum points to form a core point.
Returns

JSON with labels (−1 = noise), n_clusters, n_noise.

Algorithm

A point $p$ is a core point if $|\mathcal{N}_{\varepsilon}(p)| \geq m$. Clusters are connected components of core points.

Example
import seraplot as sp, numpy as np
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.6)
result = sp.DBSCAN(eps=0.8, min_samples=5).fit_predict(X)
print(result)

Référence API

Nom de fonction JSON

ml_dbscan_fit_predict — alias : dbscan_fit_predict, ml_dbscan

Classe Python
sp.DbscanFitPredict(eps=0.5, min_samples=5)
Paramètres du constructeur
ParamètreTypeDéfautDescription
epsfloat0.5Rayon de voisinage.
min_samplesint5Minimum de points pour former un point noyau.
Retourne

JSON avec labels (−1 = bruit), n_clusters, n_noise.

Algorithme

Un point $p$ est un point noyau si $|\mathcal{N}_{\varepsilon}(p)| \geq m$. Les clusters sont des composantes connexes de points noyaux.

Exemple
import seraplot as sp, numpy as np
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.6)
result = sp.DBSCAN(eps=0.8, min_samples=5).fit_predict(X)
print(result)

Linear Models

EN — Linear models for regression and classification with various regularisations.

FR — Modèles linéaires pour la régression et la classification avec différentes régularisations.

Contents

LinearRegression

Regressor sklearn-compatible 📈 Linear

Ordinary Least Squares linear regression — analytical Gram/Cholesky solver. / Régression linéaire par moindres carrés ordinaires — solveur analytique Gram/Cholesky.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(500, 4)
y = X @ [2, -1, 0.5, 1.5] + np.random.randn(500) * 0.3
model = sp.LinearRegression()
model.fit(X, y)
print(model.coef_, model.intercept_, model.score(X, y))
💡
EN — Drop-in replacement: sp.LinearRegression has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_linear_regression — aliases: linear_regression, linreg

Python class
sp.LinearRegression(fit_intercept=true)
Constructor Parameters
ParameterTypeDefaultDescription
fit_interceptbooltrueFit an intercept term.
Returns

JSON with predictions, coef, intercept.

Algorithm

$$\hat{\beta} = (X^T X)^{-1} X^T y$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(500, 4)
y = X @ [2, -1, 0.5, 1.5] + np.random.randn(500) * 0.3
model = sp.LinearRegression()
model.fit(X, y)
print(model.coef_, model.intercept_, model.score(X, y))

Référence API

Nom de fonction JSON

ml_linear_regression — alias : linear_regression, linreg

Classe Python
sp.LinearRegression(fit_intercept=true)
Paramètres du constructeur
ParamètreTypeDéfautDescription
fit_interceptbooltrueAjuster un terme d'intercept.
Retourne

JSON avec predictions, coef, intercept.

Algorithme

$$\hat{\beta} = (X^T X)^{-1} X^T y$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(500, 4)
y = X @ [2, -1, 0.5, 1.5] + np.random.randn(500) * 0.3
model = sp.LinearRegression()
model.fit(X, y)
print(model.coef_, model.intercept_, model.score(X, y))

Ridge

Regressor sklearn-compatible 📈 Linear

Ridge regression — L2-penalised OLS with Cholesky solver. / Régression Ridge — OLS pénalisée L2 avec solveur Cholesky.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(300, 5)
y = X @ np.array([1, -2, 0.5, 1.5, -0.8]) + np.random.randn(300)
reg = sp.Ridge(alpha=0.5)
reg.fit(X, y)
print(f"R²: {reg.score(X, y):.4f}")
💡
EN — Drop-in replacement: sp.Ridge has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_ridge — aliases: ridge, ridge_regression

Python class
sp.Ridge(alpha=1.0, fit_intercept=true)
Constructor Parameters
ParameterTypeDefaultDescription
alphafloat1.0L2 regularisation strength.
fit_interceptbooltrueFit an intercept term.
Returns

JSON with predictions, coef, intercept.

Algorithm

$$\hat{\beta} = (X^TX + \alpha I)^{-1}X^Ty$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(300, 5)
y = X @ np.array([1, -2, 0.5, 1.5, -0.8]) + np.random.randn(300)
reg = sp.Ridge(alpha=0.5)
reg.fit(X, y)
print(f"R²: {reg.score(X, y):.4f}")

Référence API

Nom de fonction JSON

ml_ridge — alias : ridge, ridge_regression

Classe Python
sp.Ridge(alpha=1.0, fit_intercept=true)
Paramètres du constructeur
ParamètreTypeDéfautDescription
alphafloat1.0Force de régularisation L2.
fit_interceptbooltrueAjuster un terme d'intercept.
Retourne

JSON avec predictions, coef, intercept.

Algorithme

$$\hat{\beta} = (X^TX + \alpha I)^{-1}X^Ty$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(300, 5)
y = X @ [1, -2, 0.5, 1.5, -0.8] + np.random.randn(300)
reg = sp.Ridge(alpha=0.5)
reg.fit(X, y)
print(f"R² : {reg.score(X, y):.4f}")

RidgeClassifier

Classifier sklearn-compatible 📈 Linear

Ridge classifier — one-vs-rest Ridge regression mapped to class labels. / Classificateur Ridge — régression Ridge one-vs-rest mappée en labels.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(300, 5)
y = (X[:, 0] - X[:, 2] > 0).astype(int)
clf = sp.RidgeClassifier(alpha=1.0)
clf.fit(X, y)
print(f"Accuracy: {clf.score(X, y):.3f}")
💡
EN — Drop-in replacement: sp.RidgeClassifier has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_ridge_classifier — aliases: ridge_classifier, ridge_cls

Python class
sp.RidgeClassifier(alpha=1.0)
Constructor Parameters
ParameterTypeDefaultDescription
alphafloat1.0L2 regularisation strength.
Returns

JSON with predictions.

Algorithm

$$\hat{y} = \text{sign}(X\hat{\beta}), \quad \hat{\beta} = (X^TX + \alpha I)^{-1}X^TY$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(300, 5)
y = (X[:, 0] - X[:, 2] > 0).astype(int)
clf = sp.RidgeClassifier(alpha=1.0)
clf.fit(X, y)
print(f"Accuracy: {clf.score(X, y):.3f}")

Référence API

Nom de fonction JSON

ml_ridge_classifier — alias : ridge_classifier, ridge_cls

Classe Python
sp.RidgeClassifier(alpha=1.0)
Paramètres du constructeur
ParamètreTypeDéfautDescription
alphafloat1.0Force de régularisation L2.
Retourne

JSON avec predictions.

Algorithme

$$\hat{y} = \text{sign}(X\hat{\beta}), \quad \hat{\beta} = (X^TX + \alpha I)^{-1}X^TY$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(300, 5)
y = (X[:, 0] - X[:, 2] > 0).astype(int)
clf = sp.RidgeClassifier(alpha=1.0)
clf.fit(X, y)
print(f"Précision : {clf.score(X, y):.3f}")

Lasso

Regressor sklearn-compatible 📈 Linear

Lasso regression — L1-penalised OLS via coordinate descent. / Régression Lasso — OLS pénalisée L1 par descente de coordonnées.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(200, 10)
y = X[:, 0] * 2 + X[:, 3] * -1.5 + np.random.randn(200) * 0.3
model = sp.Lasso(alpha=0.1)
model.fit(X, y)
print([f"{c:.3f}" for c in model.coef_])
💡
EN — Drop-in replacement: sp.Lasso has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_lasso — aliases: lasso

Python class
sp.Lasso(alpha=1.0, max_iter=1000, tol=1e-4, fit_intercept=true)
Constructor Parameters
ParameterTypeDefaultDescription
alphafloat1.0L1 regularisation strength.
max_iterint1000Maximum iterations.
tolfloat1e-4Convergence tolerance.
fit_interceptbooltrueFit an intercept term.
Returns

JSON with predictions, coef, intercept.

Algorithm

$$\hat{\beta} = \arg\min_{\beta}|y - X\beta|_2^2 + \alpha|\beta|_1$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(200, 10)
y = X[:, 0] * 2 + X[:, 3] * -1.5 + np.random.randn(200) * 0.3
model = sp.Lasso(alpha=0.1)
model.fit(X, y)
print([f"{c:.3f}" for c in model.coef_])

Référence API

Nom de fonction JSON

ml_lasso — alias : lasso

Classe Python
sp.Lasso(alpha=1.0, max_iter=1000, tol=1e-4, fit_intercept=true)
Paramètres du constructeur
ParamètreTypeDéfautDescription
alphafloat1.0Force de régularisation L1.
max_iterint1000Nombre maximum d'itérations.
tolfloat1e-4Tolérance de convergence.
fit_interceptbooltrueAjuster un terme d'intercept.
Retourne

JSON avec predictions, coef, intercept.

Algorithme

$$\hat{\beta} = \arg\min_{\beta}|y - X\beta|_2^2 + \alpha|\beta|_1$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(200, 10)
y = X[:, 0] * 2 + X[:, 3] * -1.5 + np.random.randn(200) * 0.3
model = sp.Lasso(alpha=0.1)
model.fit(X, y)
print([f"{c:.3f}" for c in model.coef_])

ElasticNet

Regressor sklearn-compatible 📈 Linear

ElasticNet — combined L1 + L2 regularisation via coordinate descent. / ElasticNet — régularisation combinée L1 + L2 par descente de coordonnées.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(300, 8)
y = X[:, 0] - X[:, 2] * 0.5 + np.random.randn(300) * 0.4
model = sp.ElasticNet(alpha=0.5, l1_ratio=0.7)
model.fit(X, y)
print(model.score(X, y))
💡
EN — Drop-in replacement: sp.ElasticNet has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_elastic_net — aliases: elastic_net, elasticnet

Python class
sp.ElasticNet(alpha=1.0, l1_ratio=0.5, max_iter=1000, tol=1e-4, fit_intercept=true)
Constructor Parameters
ParameterTypeDefaultDescription
alphafloat1.0Overall regularisation strength.
l1_ratiofloat0.5L1 mix (0 = Ridge, 1 = Lasso).
max_iterint1000Maximum iterations.
tolfloat1e-4Convergence tolerance.
fit_interceptbooltrueFit an intercept term.
Returns

JSON with predictions, coef, intercept.

Algorithm

$$\hat{\beta} = \arg\min_{\beta}|y-X\beta|_2^2 + \alpha\rho|\beta|_1 + \frac{\alpha(1-\rho)}{2}|\beta|_2^2$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(300, 8)
y = X[:, 0] - X[:, 2] * 0.5 + np.random.randn(300) * 0.4
model = sp.ElasticNet(alpha=0.5, l1_ratio=0.7)
model.fit(X, y)
print(model.score(X, y))

Référence API

Nom de fonction JSON

ml_elastic_net — alias : elastic_net, elasticnet

Classe Python
sp.ElasticNet(alpha=1.0, l1_ratio=0.5, max_iter=1000, tol=1e-4, fit_intercept=true)
Paramètres du constructeur
ParamètreTypeDéfautDescription
alphafloat1.0Force globale de régularisation.
l1_ratiofloat0.5Mix L1 (0 = Ridge, 1 = Lasso).
max_iterint1000Nombre maximum d'itérations.
tolfloat1e-4Tolérance de convergence.
fit_interceptbooltrueAjuster un terme d'intercept.
Retourne

JSON avec predictions, coef, intercept.

Algorithme

$$\hat{\beta} = \arg\min_{\beta}|y-X\beta|_2^2 + \alpha\rho|\beta|_1 + \frac{\alpha(1-\rho)}{2}|\beta|_2^2$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(300, 8)
y = X[:, 0] - X[:, 2] * 0.5 + np.random.randn(300) * 0.4
model = sp.ElasticNet(alpha=0.5, l1_ratio=0.7)
model.fit(X, y)
print(model.score(X, y))

LogisticRegression

Classifier sklearn-compatible 📈 Linear

Logistic regression — L2-regularised binary/multiclass via Newton-CG. / Régression logistique — binaire/multi-classe L2 via Newton-CG.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(400, 4)
y = (X[:, 0] + X[:, 1] > 0).astype(int)
model = sp.LogisticRegression(C=1.0)
model.fit(X, y)
print(f"Accuracy: {model.score(X, y):.3f}")
💡
EN — Drop-in replacement: sp.LogisticRegression has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_logistic_regression — aliases: logistic_regression, logistic

Python class
sp.LogisticRegression(C=1.0, max_iter=100, tol=1e-4, fit_intercept=true)
Constructor Parameters
ParameterTypeDefaultDescription
Cfloat1.0Inverse regularisation strength (larger = less reg).
max_iterint100Maximum iterations.
tolfloat1e-4Convergence tolerance.
fit_interceptbooltrueFit an intercept term.
Returns

JSON with predictions, coef, intercept, classes.

Algorithm

$$P(y=1|x) = \sigma(x^T\beta + b), \quad \sigma(z) = \frac{1}{1+e^{-z}}$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(400, 4)
y = (X[:, 0] + X[:, 1] > 0).astype(int)
model = sp.LogisticRegression(C=1.0)
model.fit(X, y)
print(f"Accuracy: {model.score(X, y):.3f}")

Référence API

Nom de fonction JSON

ml_logistic_regression — alias : logistic_regression, logistic

Classe Python
sp.LogisticRegression(C=1.0, max_iter=100, tol=1e-4, fit_intercept=true)
Paramètres du constructeur
ParamètreTypeDéfautDescription
Cfloat1.0Force de régularisation inverse (plus grand = moins de régul.).
max_iterint100Nombre maximum d'itérations.
tolfloat1e-4Tolérance de convergence.
fit_interceptbooltrueAjuster un terme d'intercept.
Retourne

JSON avec predictions, coef, intercept, classes.

Algorithme

$$P(y=1|x) = \sigma(x^T\beta + b), \quad \sigma(z) = \frac{1}{1+e^{-z}}$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(400, 4)
y = (X[:, 0] + X[:, 1] > 0).astype(int)
model = sp.LogisticRegression(C=1.0)
model.fit(X, y)
print(f"Précision : {model.score(X, y):.3f}")

SgdClassifier

Classifier sklearn-compatible 📈 Linear

SGDClassifier — stochastic gradient descent for linear classifiers. / SGDClassifier — descente de gradient stochastique pour classifieurs linéaires.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(1000, 5)
y = (X[:, 0] > 0).astype(int)
clf = sp.SGDClassifier(loss="hinge", alpha=1e-4)
clf.fit(X, y)
print(clf.score(X, y))
💡
EN — Drop-in replacement: sp.SgdClassifier has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_sgd_classifier — aliases: sgd_classifier, sgd_cls

Python class
sp.SgdClassifier(loss=hinge, alpha=0.0001, max_iter=1000, tol=1e-3, eta0=1.0, fit_intercept=true)
Constructor Parameters
ParameterTypeDefaultDescription
lossstrhingeLoss: `hinge`, `log`, `modified_huber`, `squared_hinge`.
alphafloat0.0001Regularisation multiplier.
max_iterint1000Maximum passes over the data.
tolfloat1e-3Convergence tolerance.
eta0float1.0Initial learning rate.
fit_interceptbooltrueFit an intercept term.
Returns

JSON with predictions, coef, intercept.

Algorithm

$$\beta_{t+1} = \beta_t - \eta_t \nabla_{\beta} L(y_i, x_i^T\beta_t)$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(1000, 5)
y = (X[:, 0] > 0).astype(int)
clf = sp.SGDClassifier(loss="hinge", alpha=1e-4)
clf.fit(X, y)
print(clf.score(X, y))

Référence API

Nom de fonction JSON

ml_sgd_classifier — alias : sgd_classifier, sgd_cls

Classe Python
sp.SgdClassifier(loss=hinge, alpha=0.0001, max_iter=1000, tol=1e-3, eta0=1.0, fit_intercept=true)
Paramètres du constructeur
ParamètreTypeDéfautDescription
lossstrhingePerte : `hinge`, `log`, `modified_huber`, `squared_hinge`.
alphafloat0.0001Multiplicateur de régularisation.
max_iterint1000Nombre maximum de passes sur les données.
tolfloat1e-3Tolérance de convergence.
eta0float1.0Taux d'apprentissage initial.
fit_interceptbooltrueAjuster un terme d'intercept.
Retourne

JSON avec predictions, coef, intercept.

Algorithme

$$\beta_{t+1} = \beta_t - \eta_t \nabla_{\beta} L(y_i, x_i^T\beta_t)$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(1000, 5)
y = (X[:, 0] > 0).astype(int)
clf = sp.SGDClassifier(loss="hinge", alpha=1e-4)
clf.fit(X, y)
print(clf.score(X, y))

SgdRegressor

Regressor sklearn-compatible 📈 Linear

SGDRegressor — stochastic gradient descent for linear regressors. / SGDRegressor — descente de gradient stochastique pour régresseurs linéaires.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(1000, 3)
y = X @ [1.5, -0.5, 2.0] + np.random.randn(1000) * 0.5
reg = sp.SGDRegressor(alpha=1e-4, max_iter=500)
reg.fit(X, y)
print(reg.score(X, y))
💡
EN — Drop-in replacement: sp.SgdRegressor has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_sgd_regressor — aliases: sgd_regressor, sgd_reg

Python class
sp.SgdRegressor(alpha=0.0001, max_iter=1000, tol=1e-3, eta0=0.1, fit_intercept=true)
Constructor Parameters
ParameterTypeDefaultDescription
alphafloat0.0001Regularisation multiplier.
max_iterint1000Maximum passes.
tolfloat1e-3Convergence tolerance.
eta0float0.1Initial learning rate.
fit_interceptbooltrueFit an intercept.
Returns

JSON with predictions, coef, intercept.

Algorithm

$$\beta_{t+1} = \beta_t - \eta_t \cdot 2(\hat{y}_i - y_i) x_i$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(1000, 3)
y = X @ [1.5, -0.5, 2.0] + np.random.randn(1000) * 0.5
reg = sp.SGDRegressor(alpha=1e-4, max_iter=500)
reg.fit(X, y)
print(reg.score(X, y))

Référence API

Nom de fonction JSON

ml_sgd_regressor — alias : sgd_regressor, sgd_reg

Classe Python
sp.SgdRegressor(alpha=0.0001, max_iter=1000, tol=1e-3, eta0=0.1, fit_intercept=true)
Paramètres du constructeur
ParamètreTypeDéfautDescription
alphafloat0.0001Multiplicateur de régularisation.
max_iterint1000Nombre maximum de passes.
tolfloat1e-3Tolérance de convergence.
eta0float0.1Taux d'apprentissage initial.
fit_interceptbooltrueAjuster un intercept.
Retourne

JSON avec predictions, coef, intercept.

Algorithme

$$\beta_{t+1} = \beta_t - \eta_t \cdot 2(\hat{y}_i - y_i) x_i$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(1000, 3)
y = X @ [1.5, -0.5, 2.0] + np.random.randn(1000) * 0.5
reg = sp.SGDRegressor(alpha=1e-4, max_iter=500)
reg.fit(X, y)
print(reg.score(X, y))

Tree-Based Models

EN — Decision trees and ensemble methods based on tree structures.

FR — Arbres de décision et méthodes d'ensemble basées sur des structures d'arbres.

Contents

DecisionTreeClassifier

Classifier sklearn-compatible 🌲 Tree-Based

Decision tree classifier — CART with Gini/Entropy criterion, binned splits. / Arbre de décision classifieur — CART avec critère Gini/Entropie, splits binnés.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
tree = sp.DecisionTreeClassifier(max_depth=4)
tree.fit(X, y)
print(f"Accuracy: {tree.score(X, y):.3f}")
💡
EN — Drop-in replacement: sp.DecisionTreeClassifier has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_decision_tree_classifier — aliases: decision_tree_classifier, dt_cls

Python class
sp.DecisionTreeClassifier(max_depth=∞, min_samples_split=2, min_samples_leaf=1, max_features=null, criterion=gini)
Constructor Parameters
ParameterTypeDefaultDescription
max_depthintMaximum tree depth.
min_samples_splitint2Minimum samples to split a node.
min_samples_leafint1Minimum samples in a leaf.
max_featuresint|strnullMax features per split (int or `sqrt`/`log2`).
criterionstrginiSplit criterion: `gini` or `entropy`.
Returns

JSON with predictions, feature_importances, classes.

Algorithm

$$\text{Gini}(t) = 1 - \sum_{k} p_k^2$$

Example
import seraplot as sp, numpy as np
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
tree = sp.DecisionTreeClassifier(max_depth=4)
tree.fit(X, y)
print(f"Accuracy: {tree.score(X, y):.3f}")

Référence API

Nom de fonction JSON

ml_decision_tree_classifier — alias : decision_tree_classifier, dt_cls

Classe Python
sp.DecisionTreeClassifier(max_depth=∞, min_samples_split=2, min_samples_leaf=1, max_features=null, criterion=gini)
Paramètres du constructeur
ParamètreTypeDéfautDescription
max_depthintProfondeur maximale de l'arbre.
min_samples_splitint2Minimum d'échantillons pour diviser un nœud.
min_samples_leafint1Minimum d'échantillons dans une feuille.
max_featuresint|strnullMax features par split (int ou `sqrt`/`log2`).
criterionstrginiCritère de split : `gini` ou `entropy`.
Retourne

JSON avec predictions, feature_importances, classes.

Algorithme

$$\text{Gini}(t) = 1 - \sum_{k} p_k^2$$

Exemple
import seraplot as sp, numpy as np
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
tree = sp.DecisionTreeClassifier(max_depth=4)
tree.fit(X, y)
print(f"Précision : {tree.score(X, y):.3f}")

DecisionTreeRegressor

Regressor sklearn-compatible 🌲 Tree-Based

Decision tree regressor — CART with MSE variance reduction, binned splits. / Arbre de décision régresseur — CART avec réduction de variance MSE, splits binnés.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(400, 4)
y = X[:, 0] ** 2 + X[:, 1] - X[:, 2] + np.random.randn(400) * 0.5
tree = sp.DecisionTreeRegressor(max_depth=5)
tree.fit(X, y)
print(tree.score(X, y))
💡
EN — Drop-in replacement: sp.DecisionTreeRegressor has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_decision_tree_regressor — aliases: decision_tree_regressor, dt_reg

Python class
sp.DecisionTreeRegressor(max_depth=∞, min_samples_split=2, min_samples_leaf=1, max_features=null)
Constructor Parameters
ParameterTypeDefaultDescription
max_depthintMaximum tree depth.
min_samples_splitint2Minimum samples to split a node.
min_samples_leafint1Minimum samples in a leaf.
max_featuresint|strnullMax features per split.
Returns

JSON with predictions, feature_importances.

Algorithm

$$\text{MSE}(t) = \frac{1}{n_t}\sum_{i \in t}(y_i - \bar{y}_t)^2$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(400, 4)
y = X[:, 0] ** 2 + X[:, 1] - X[:, 2] + np.random.randn(400) * 0.5
tree = sp.DecisionTreeRegressor(max_depth=5)
tree.fit(X, y)
print(tree.score(X, y))

Référence API

Nom de fonction JSON

ml_decision_tree_regressor — alias : decision_tree_regressor, dt_reg

Classe Python
sp.DecisionTreeRegressor(max_depth=∞, min_samples_split=2, min_samples_leaf=1, max_features=null)
Paramètres du constructeur
ParamètreTypeDéfautDescription
max_depthintProfondeur maximale de l'arbre.
min_samples_splitint2Minimum d'échantillons pour diviser un nœud.
min_samples_leafint1Minimum d'échantillons dans une feuille.
max_featuresint|strnullMax features par split.
Retourne

JSON avec predictions, feature_importances.

Algorithme

$$\text{MSE}(t) = \frac{1}{n_t}\sum_{i \in t}(y_i - \bar{y}_t)^2$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(400, 4)
y = X[:, 0] ** 2 + X[:, 1] - X[:, 2] + np.random.randn(400) * 0.5
tree = sp.DecisionTreeRegressor(max_depth=5)
tree.fit(X, y)
print(tree.score(X, y))

RandomForestClassifier

Classifier sklearn-compatible 🌲 Tree-Based

Random Forest classifier — bagging of CART trees with feature subsampling. / Random Forest classifieur — bagging d'arbres CART avec sous-échantillonnage de features.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
rf = sp.RandomForestClassifier(n_estimators=100, max_depth=6)
rf.fit(X, y)
print(rf.score(X, y), rf.feature_importances_)
💡
EN — Drop-in replacement: sp.RandomForestClassifier has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_random_forest_classifier — aliases: random_forest_classifier, rf_cls

Python class
sp.RandomForestClassifier(n_estimators=100, max_depth=∞, min_samples_split=2, min_samples_leaf=1, max_features=sqrt)
Constructor Parameters
ParameterTypeDefaultDescription
n_estimatorsint100Number of trees.
max_depthintMaximum tree depth.
min_samples_splitint2Min samples to split a node.
min_samples_leafint1Min samples in a leaf.
max_featuresstrsqrtFeatures per split: `sqrt`, `log2`, `all`, or int.
Returns

JSON with predictions, feature_importances.

Algorithm

$$\hat{y} = \text{majority}{h_b(x)}_{b=1}^{B}$$

Example
import seraplot as sp
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
rf = sp.RandomForestClassifier(n_estimators=100, max_depth=6)
rf.fit(X, y)
print(rf.score(X, y), rf.feature_importances_)

Référence API

Nom de fonction JSON

ml_random_forest_classifier — alias : random_forest_classifier, rf_cls

Classe Python
sp.RandomForestClassifier(n_estimators=100, max_depth=∞, min_samples_split=2, min_samples_leaf=1, max_features=sqrt)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_estimatorsint100Nombre d'arbres.
max_depthintProfondeur maximale.
min_samples_splitint2Min d'échantillons pour diviser.
min_samples_leafint1Min d'échantillons en feuille.
max_featuresstrsqrtFeatures par split : `sqrt`, `log2`, `all`, ou int.
Retourne

JSON avec predictions, feature_importances.

Algorithme

$$\hat{y} = \text{majority}{h_b(x)}_{b=1}^{B}$$

Exemple
import seraplot as sp
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
rf = sp.RandomForestClassifier(n_estimators=100, max_depth=6)
rf.fit(X, y)
print(rf.score(X, y), rf.feature_importances_)

RandomForestRegressor

Regressor sklearn-compatible 🌲 Tree-Based

Random Forest regressor — averaged ensemble of CART trees. / Random Forest régresseur — ensemble moyenné d'arbres CART.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(500, 6)
y = X[:, 0] ** 2 + X[:, 1] * X[:, 2] + np.random.randn(500) * 0.3
rf = sp.RandomForestRegressor(n_estimators=50, max_depth=8)
rf.fit(X, y)
print(rf.score(X, y))
💡
EN — Drop-in replacement: sp.RandomForestRegressor has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_random_forest_regressor — aliases: random_forest_regressor, rf_reg

Python class
sp.RandomForestRegressor(n_estimators=100, max_depth=∞, min_samples_split=2, min_samples_leaf=1, max_features=sqrt)
Constructor Parameters
ParameterTypeDefaultDescription
n_estimatorsint100Number of trees.
max_depthintMaximum tree depth.
min_samples_splitint2Min samples to split.
min_samples_leafint1Min samples in leaf.
max_featuresstrsqrtFeatures per split.
Returns

JSON with predictions, feature_importances.

Algorithm

$$\hat{y} = \frac{1}{B}\sum_{b=1}^{B} h_b(x)$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(500, 6)
y = X[:, 0] ** 2 + X[:, 1] * X[:, 2] + np.random.randn(500) * 0.3
rf = sp.RandomForestRegressor(n_estimators=50, max_depth=8)
rf.fit(X, y)
print(rf.score(X, y))

Référence API

Nom de fonction JSON

ml_random_forest_regressor — alias : random_forest_regressor, rf_reg

Classe Python
sp.RandomForestRegressor(n_estimators=100, max_depth=∞, min_samples_split=2, min_samples_leaf=1, max_features=sqrt)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_estimatorsint100Nombre d'arbres.
max_depthintProfondeur maximale.
min_samples_splitint2Min d'échantillons pour diviser.
min_samples_leafint1Min d'échantillons en feuille.
max_featuresstrsqrtFeatures par split.
Retourne

JSON avec predictions, feature_importances.

Algorithme

$$\hat{y} = \frac{1}{B}\sum_{b=1}^{B} h_b(x)$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(500, 6)
y = X[:, 0] ** 2 + X[:, 1] * X[:, 2] + np.random.randn(500) * 0.3
rf = sp.RandomForestRegressor(n_estimators=50, max_depth=8)
rf.fit(X, y)
print(rf.score(X, y))

GradientBoostingClassifier

Classifier sklearn-compatible 🌲 Tree-Based

Gradient Boosting classifier — sequential additive model with log-loss. / Gradient Boosting classifieur — modèle additif séquentiel avec log-loss.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=500, n_features=10)
gb = sp.GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)
gb.fit(X, y)
print(gb.score(X, y))
💡
EN — Drop-in replacement: sp.GradientBoostingClassifier has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_gradient_boosting_classifier — aliases: gradient_boosting_classifier, gb_cls

Python class
sp.GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=3, min_samples_split=2, min_samples_leaf=1)
Constructor Parameters
ParameterTypeDefaultDescription
n_estimatorsint100Number of boosting rounds.
learning_ratefloat0.1Shrinkage applied to each tree.
max_depthint3Maximum tree depth.
min_samples_splitint2Min samples to split.
min_samples_leafint1Min samples in leaf.
Returns

JSON with predictions.

Algorithm

$$F_m(x) = F_{m-1}(x) + \eta \cdot h_m(x)$$

Example
import seraplot as sp
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=500, n_features=10)
gb = sp.GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)
gb.fit(X, y)
print(gb.score(X, y))

Référence API

Nom de fonction JSON

ml_gradient_boosting_classifier — alias : gradient_boosting_classifier, gb_cls

Classe Python
sp.GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=3, min_samples_split=2, min_samples_leaf=1)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_estimatorsint100Nombre de tours de boosting.
learning_ratefloat0.1Shrinkage appliqué à chaque arbre.
max_depthint3Profondeur maximale de chaque arbre.
min_samples_splitint2Min d'échantillons pour diviser.
min_samples_leafint1Min d'échantillons en feuille.
Retourne

JSON avec predictions.

Algorithme

$$F_m(x) = F_{m-1}(x) + \eta \cdot h_m(x)$$

Exemple
import seraplot as sp
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=500, n_features=10)
gb = sp.GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)
gb.fit(X, y)
print(gb.score(X, y))

GradientBoostingRegressor

Regressor sklearn-compatible 🌲 Tree-Based

Gradient Boosting regressor — sequential additive model minimising MSE. / Gradient Boosting régresseur — modèle additif séquentiel minimisant la MSE.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(400, 5)
y = X[:, 0] ** 2 - X[:, 1] + np.random.randn(400) * 0.3
gb = sp.GradientBoostingRegressor(n_estimators=100, learning_rate=0.05)
gb.fit(X, y)
print(gb.score(X, y))
💡
EN — Drop-in replacement: sp.GradientBoostingRegressor has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_gradient_boosting_regressor — aliases: gradient_boosting_regressor, gb_reg

Python class
sp.GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=3, min_samples_split=2, min_samples_leaf=1)
Constructor Parameters
ParameterTypeDefaultDescription
n_estimatorsint100Number of boosting rounds.
learning_ratefloat0.1Shrinkage applied to each tree.
max_depthint3Maximum tree depth.
min_samples_splitint2Min samples to split.
min_samples_leafint1Min samples in leaf.
Returns

JSON with predictions.

Algorithm

$$F_m(x) = F_{m-1}(x) + \eta \cdot h_m(x), \quad h_m = \arg\min_h \sum_i(r_i - h(x_i))^2$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(400, 5)
y = X[:, 0] ** 2 - X[:, 1] + np.random.randn(400) * 0.3
gb = sp.GradientBoostingRegressor(n_estimators=100, learning_rate=0.05)
gb.fit(X, y)
print(gb.score(X, y))

Référence API

Nom de fonction JSON

ml_gradient_boosting_regressor — alias : gradient_boosting_regressor, gb_reg

Classe Python
sp.GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=3, min_samples_split=2, min_samples_leaf=1)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_estimatorsint100Nombre de tours de boosting.
learning_ratefloat0.1Shrinkage appliqué à chaque arbre.
max_depthint3Profondeur maximale.
min_samples_splitint2Min d'échantillons pour diviser.
min_samples_leafint1Min d'échantillons en feuille.
Retourne

JSON avec predictions.

Algorithme

$$F_m(x) = F_{m-1}(x) + \eta \cdot h_m(x), \quad r_i = y_i - F_{m-1}(x_i)$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(400, 5)
y = X[:, 0] ** 2 - X[:, 1] + np.random.randn(400) * 0.3
gb = sp.GradientBoostingRegressor(n_estimators=100, learning_rate=0.05)
gb.fit(X, y)
print(gb.score(X, y))

AdaboostClassifier

Classifier sklearn-compatible 🌲 Tree-Based

AdaBoost classifier — adaptive boosting with weighted decision stumps. / AdaBoost classifieur — boosting adaptatif avec stumps de décision pondérés.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=500, n_features=8)
ada = sp.AdaBoostClassifier(n_estimators=50)
ada.fit(X, y)
print(ada.score(X, y))
💡
EN — Drop-in replacement: sp.AdaboostClassifier has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_adaboost_classifier — aliases: adaboost_classifier, ada_cls

Python class
sp.AdaboostClassifier(n_estimators=50, learning_rate=1.0, max_depth=1)
Constructor Parameters
ParameterTypeDefaultDescription
n_estimatorsint50Number of weak learners.
learning_ratefloat1.0Shrinkage of each weak learner.
max_depthint1Depth of each base tree.
Returns

JSON with predictions.

Algorithm

$$F(x) = \text{sign}\left(\sum_{m=1}^{M} \alpha_m h_m(x)\right)$$

Example
import seraplot as sp
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=500, n_features=8)
ada = sp.AdaBoostClassifier(n_estimators=50)
ada.fit(X, y)
print(ada.score(X, y))

Référence API

Nom de fonction JSON

ml_adaboost_classifier — alias : adaboost_classifier, ada_cls

Classe Python
sp.AdaboostClassifier(n_estimators=50, learning_rate=1.0, max_depth=1)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_estimatorsint50Nombre d'apprenants faibles.
learning_ratefloat1.0Shrinkage de chaque apprenant faible.
max_depthint1Profondeur de chaque arbre de base.
Retourne

JSON avec predictions.

Algorithme

$$F(x) = \text{sign}\left(\sum_{m=1}^{M} \alpha_m h_m(x)\right)$$

Exemple
import seraplot as sp
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=500, n_features=8)
ada = sp.AdaBoostClassifier(n_estimators=50)
ada.fit(X, y)
print(ada.score(X, y))

AdaboostRegressor

Regressor sklearn-compatible 🌲 Tree-Based

AdaBoost regressor — adaptive boosting with median-weighted aggregation. / AdaBoost régresseur — boosting adaptatif avec agrégation pondérée par la médiane.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(400, 4)
y = X[:, 0] ** 2 + np.random.randn(400) * 0.3
ada = sp.AdaBoostRegressor(n_estimators=50, learning_rate=0.8)
ada.fit(X, y)
print(ada.score(X, y))
💡
EN — Drop-in replacement: sp.AdaboostRegressor has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_adaboost_regressor — aliases: adaboost_regressor, ada_reg

Python class
sp.AdaboostRegressor(n_estimators=50, learning_rate=1.0, max_depth=3)
Constructor Parameters
ParameterTypeDefaultDescription
n_estimatorsint50Number of weak learners.
learning_ratefloat1.0Shrinkage of each weak learner.
max_depthint3Depth of each base tree.
Returns

JSON with predictions.

Algorithm

$$\hat{y} = \text{weighted median}{h_m(x), w_m}_{m=1}^{M}$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(400, 4)
y = X[:, 0] ** 2 + np.random.randn(400) * 0.3
ada = sp.AdaBoostRegressor(n_estimators=50, learning_rate=0.8)
ada.fit(X, y)
print(ada.score(X, y))

Référence API

Nom de fonction JSON

ml_adaboost_regressor — alias : adaboost_regressor, ada_reg

Classe Python
sp.AdaboostRegressor(n_estimators=50, learning_rate=1.0, max_depth=3)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_estimatorsint50Nombre d'apprenants faibles.
learning_ratefloat1.0Shrinkage de chaque apprenant faible.
max_depthint3Profondeur de chaque arbre de base.
Retourne

JSON avec predictions.

Algorithme

$$\hat{y} = \text{médiane pondérée}{h_m(x), w_m}_{m=1}^{M}$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(400, 4)
y = X[:, 0] ** 2 + np.random.randn(400) * 0.3
ada = sp.AdaBoostRegressor(n_estimators=50, learning_rate=0.8)
ada.fit(X, y)
print(ada.score(X, y))

Neighbors

EN — Instance-based learning methods using nearest neighbor search.

FR — Méthodes d'apprentissage par instances utilisant la recherche de voisins les plus proches.

Contents

KnnClassifier

Classifier sklearn-compatible 🔍 Neighbors

K-Nearest Neighbors classifier — majority vote among k nearest neighbors. / K plus proches voisins classifieur — vote majoritaire parmi les k voisins les plus proches.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
knn = sp.KNeighborsClassifier(n_neighbors=5)
knn.fit(X, y)
print(knn.score(X, y))
💡
EN — Drop-in replacement: sp.KnnClassifier has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_knn_classifier — aliases: knn_classifier, knn_cls

Python class
sp.KnnClassifier(n_neighbors=5, weights=uniform)
Constructor Parameters
ParameterTypeDefaultDescription
n_neighborsint5Number of nearest neighbors.
weightsstruniformWeighting: `uniform` or `distance`.
Returns

JSON with predictions.

Algorithm

$$\hat{y} = \arg\max_c \sum_{i \in \mathcal{N}_k(x)} w_i \mathbf{1}[y_i = c]$$

Example
import seraplot as sp
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
knn = sp.KNeighborsClassifier(n_neighbors=5)
knn.fit(X, y)
print(knn.score(X, y))

Référence API

Nom de fonction JSON

ml_knn_classifier — alias : knn_classifier, knn_cls

Classe Python
sp.KnnClassifier(n_neighbors=5, weights=uniform)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_neighborsint5Nombre de voisins les plus proches.
weightsstruniformPondération : `uniform` ou `distance`.
Retourne

JSON avec predictions.

Algorithme

$$\hat{y} = \arg\max_c \sum_{i \in \mathcal{N}_k(x)} w_i \mathbf{1}[y_i = c]$$

Exemple
import seraplot as sp
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
knn = sp.KNeighborsClassifier(n_neighbors=5)
knn.fit(X, y)
print(knn.score(X, y))

KnnRegressor

Regressor sklearn-compatible 🔍 Neighbors

K-Nearest Neighbors regressor — weighted average of k nearest neighbors. / K plus proches voisins régresseur — moyenne pondérée des k voisins les plus proches.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(300, 3)
y = X[:, 0] ** 2 + X[:, 1] + np.random.randn(300) * 0.5
knn = sp.KNeighborsRegressor(n_neighbors=7, weights="distance")
knn.fit(X, y)
print(knn.score(X, y))
💡
EN — Drop-in replacement: sp.KnnRegressor has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_knn_regressor — aliases: knn_regressor, knn_reg

Python class
sp.KnnRegressor(n_neighbors=5, weights=uniform)
Constructor Parameters
ParameterTypeDefaultDescription
n_neighborsint5Number of nearest neighbors.
weightsstruniformWeighting: `uniform` or `distance`.
Returns

JSON with predictions.

Algorithm

$$\hat{y} = \frac{\sum_{i \in \mathcal{N}k(x)} w_i y_i}{\sum{i \in \mathcal{N}_k(x)} w_i}$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(300, 3)
y = X[:, 0] ** 2 + X[:, 1] + np.random.randn(300) * 0.5
knn = sp.KNeighborsRegressor(n_neighbors=7, weights="distance")
knn.fit(X, y)
print(knn.score(X, y))

Référence API

Nom de fonction JSON

ml_knn_regressor — alias : knn_regressor, knn_reg

Classe Python
sp.KnnRegressor(n_neighbors=5, weights=uniform)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_neighborsint5Nombre de voisins les plus proches.
weightsstruniformPondération : `uniform` ou `distance`.
Retourne

JSON avec predictions.

Algorithme

$$\hat{y} = \frac{\sum_{i \in \mathcal{N}k(x)} w_i y_i}{\sum{i \in \mathcal{N}_k(x)} w_i}$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(300, 3)
y = X[:, 0] ** 2 + X[:, 1] + np.random.randn(300) * 0.5
knn = sp.KNeighborsRegressor(n_neighbors=7, weights="distance")
knn.fit(X, y)
print(knn.score(X, y))

NearestCentroid

Classifier sklearn-compatible 🔍 Neighbors

Nearest Centroid classifier — assigns class by closest class mean. / Classificateur par centroïde le plus proche — assigne la classe par la moyenne de classe la plus proche.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
nc = sp.NearestCentroid()
nc.fit(X, y)
print(nc.score(X, y))
💡
EN — Drop-in replacement: sp.NearestCentroid has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_nearest_centroid — aliases: nearest_centroid

Python class
sp.NearestCentroid()
Constructor Parameters

No constructor parameters.

Returns

JSON with predictions.

Algorithm

$$\hat{y} = \arg\min_c |x - \mu_c|_2^2$$

Example
import seraplot as sp
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
nc = sp.NearestCentroid()
nc.fit(X, y)
print(nc.score(X, y))

Référence API

Nom de fonction JSON

ml_nearest_centroid — alias : nearest_centroid

Classe Python
sp.NearestCentroid()
Paramètres du constructeur

Aucun paramètre de constructeur.

Retourne

JSON avec predictions.

Algorithme

$$\hat{y} = \arg\min_c |x - \mu_c|_2^2$$

Exemple
import seraplot as sp
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
nc = sp.NearestCentroid()
nc.fit(X, y)
print(nc.score(X, y))

Naive Bayes

EN — Probabilistic classifiers based on Bayes theorem with feature independence.

FR — Classificateurs probabilistes basés sur le théorème de Bayes avec indépendance des features.

Contents

GaussianNb

Classifier sklearn-compatible 📊 Naive Bayes

Gaussian Naive Bayes — likelihood modelled as Gaussian per class per feature. / Naive Bayes Gaussien — vraisemblance modélisée comme Gaussienne par classe et feature.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
gnb = sp.GaussianNB()
gnb.fit(X, y)
print(gnb.score(X, y))
💡
EN — Drop-in replacement: sp.GaussianNb has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_gaussian_nb — aliases: gaussian_nb

Python class
sp.GaussianNb()
Constructor Parameters

No constructor parameters.

Returns

JSON with predictions.

Algorithm

$$P(x_j | y=c) = \frac{1}{\sqrt{2\pi\sigma_{cj}^2}} \exp!\left(-\frac{(x_j-\mu_{cj})^2}{2\sigma_{cj}^2}\right)$$

Example
import seraplot as sp
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
gnb = sp.GaussianNB()
gnb.fit(X, y)
print(gnb.score(X, y))

Référence API

Nom de fonction JSON

ml_gaussian_nb — alias : gaussian_nb

Classe Python
sp.GaussianNb()
Paramètres du constructeur

Aucun paramètre de constructeur.

Retourne

JSON avec predictions.

Algorithme

$$P(x_j | y=c) = \frac{1}{\sqrt{2\pi\sigma_{cj}^2}} \exp!\left(-\frac{(x_j-\mu_{cj})^2}{2\sigma_{cj}^2}\right)$$

Exemple
import seraplot as sp
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
gnb = sp.GaussianNB()
gnb.fit(X, y)
print(gnb.score(X, y))

MultinomialNb

Classifier sklearn-compatible 📊 Naive Bayes

Multinomial Naive Bayes — for count/frequency features (text, bag-of-words). / Naive Bayes Multinomial — pour features de comptage/fréquence (texte, sac de mots).

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randint(0, 10, size=(300, 5)).astype(float)
y = (X[:, 0] > 5).astype(int)
mnb = sp.MultinomialNB(alpha=1.0)
mnb.fit(X, y)
print(mnb.score(X, y))
💡
EN — Drop-in replacement: sp.MultinomialNb has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_multinomial_nb — aliases: multinomial_nb

Python class
sp.MultinomialNb(alpha=1.0)
Constructor Parameters
ParameterTypeDefaultDescription
alphafloat1.0Additive (Laplace) smoothing.
Returns

JSON with predictions.

Algorithm

$$P(x|y=c) = \frac{N_{cy} + \alpha}{N_c + \alpha p}$$

Example
import seraplot as sp, numpy as np
X = np.random.randint(0, 10, size=(300, 5)).astype(float)
y = (X[:, 0] > 5).astype(int)
mnb = sp.MultinomialNB(alpha=1.0)
mnb.fit(X, y)
print(mnb.score(X, y))

Référence API

Nom de fonction JSON

ml_multinomial_nb — alias : multinomial_nb

Classe Python
sp.MultinomialNb(alpha=1.0)
Paramètres du constructeur
ParamètreTypeDéfautDescription
alphafloat1.0Lissage additif (Laplace).
Retourne

JSON avec predictions.

Algorithme

$$P(x|y=c) = \frac{N_{cy} + \alpha}{N_c + \alpha p}$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randint(0, 10, size=(300, 5)).astype(float)
y = (X[:, 0] > 5).astype(int)
mnb = sp.MultinomialNB(alpha=1.0)
mnb.fit(X, y)
print(mnb.score(X, y))

BernoulliNb

Classifier sklearn-compatible 📊 Naive Bayes

Bernoulli Naive Bayes — for binary/boolean features. / Naive Bayes Bernoulli — pour features binaires/booléennes.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = (np.random.randn(400, 6) > 0).astype(float)
y = (X[:, 0] & X[:, 1]).astype(int)
bnb = sp.BernoulliNB(alpha=1.0)
bnb.fit(X, y)
print(bnb.score(X, y))
💡
EN — Drop-in replacement: sp.BernoulliNb has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_bernoulli_nb — aliases: bernoulli_nb

Python class
sp.BernoulliNb(alpha=1.0, binarize=0.0)
Constructor Parameters
ParameterTypeDefaultDescription
alphafloat1.0Additive (Laplace) smoothing.
binarizefloat0.0Threshold for binarising features.
Returns

JSON with predictions.

Algorithm

$$P(x_j|y=c) = p_{cj}^{x_j}(1-p_{cj})^{1-x_j}$$

Example
import seraplot as sp, numpy as np
X = (np.random.randn(400, 6) > 0).astype(float)
y = (X[:, 0] & X[:, 1]).astype(int)
bnb = sp.BernoulliNB(alpha=1.0)
bnb.fit(X, y)
print(bnb.score(X, y))

Référence API

Nom de fonction JSON

ml_bernoulli_nb — alias : bernoulli_nb

Classe Python
sp.BernoulliNb(alpha=1.0, binarize=0.0)
Paramètres du constructeur
ParamètreTypeDéfautDescription
alphafloat1.0Lissage additif (Laplace).
binarizefloat0.0Seuil pour binariser les features.
Retourne

JSON avec predictions.

Algorithme

$$P(x_j|y=c) = p_{cj}^{x_j}(1-p_{cj})^{1-x_j}$$

Exemple
import seraplot as sp, numpy as np
X = (np.random.randn(400, 6) > 0).astype(float)
y = (X[:, 0] & X[:, 1]).astype(int)
bnb = sp.BernoulliNB(alpha=1.0)
bnb.fit(X, y)
print(bnb.score(X, y))

Support Vector Machines

EN — Linear SVM models for classification and regression.

FR — Modèles SVM linéaires pour la classification et la régression.

Contents

LinearSvc

Classifier sklearn-compatible ⚡ SVM

LinearSVC — linear Support Vector Machine for classification via dual coordinate descent. / LinearSVC — Machine à vecteurs de support linéaire pour classification.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=500, n_features=8)
svc = sp.LinearSVC(C=1.0)
svc.fit(X, y)
print(svc.score(X, y))
💡
EN — Drop-in replacement: sp.LinearSvc has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_linear_svc — aliases: linear_svc

Python class
sp.LinearSvc(C=1.0, max_iter=1000, tol=1e-4)
Constructor Parameters
ParameterTypeDefaultDescription
Cfloat1.0Regularisation parameter (inverse margin).
max_iterint1000Maximum iterations.
tolfloat1e-4Convergence tolerance.
Returns

JSON with predictions.

Algorithm

$$\min_{w,b}\frac{1}{2}|w|^2 + C\sum_i \max(0, 1 - y_i(w^Tx_i + b))$$

Example
import seraplot as sp
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=500, n_features=8)
svc = sp.LinearSVC(C=1.0)
svc.fit(X, y)
print(svc.score(X, y))

Référence API

Nom de fonction JSON

ml_linear_svc — alias : linear_svc

Classe Python
sp.LinearSvc(C=1.0, max_iter=1000, tol=1e-4)
Paramètres du constructeur
ParamètreTypeDéfautDescription
Cfloat1.0Paramètre de régularisation (inverse de la marge).
max_iterint1000Nombre maximum d'itérations.
tolfloat1e-4Tolérance de convergence.
Retourne

JSON avec predictions.

Algorithme

$$\min_{w,b}\frac{1}{2}|w|^2 + C\sum_i \max(0, 1 - y_i(w^Tx_i + b))$$

Exemple
import seraplot as sp
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=500, n_features=8)
svc = sp.LinearSVC(C=1.0)
svc.fit(X, y)
print(svc.score(X, y))

LinearSvr

Regressor sklearn-compatible ⚡ SVM

LinearSVR — epsilon-insensitive linear Support Vector Regression. / LinearSVR — régression linéaire par vecteurs de support avec perte epsilon-insensible.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(400, 4)
y = X[:, 0] * 2 - X[:, 2] + np.random.randn(400) * 0.5
svr = sp.LinearSVR(C=1.0, epsilon=0.1)
svr.fit(X, y)
print(svr.score(X, y))
💡
EN — Drop-in replacement: sp.LinearSvr has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_linear_svr — aliases: linear_svr

Python class
sp.LinearSvr(C=1.0, epsilon=0.1, max_iter=1000, tol=1e-4)
Constructor Parameters
ParameterTypeDefaultDescription
Cfloat1.0Regularisation parameter.
epsilonfloat0.1Epsilon-tube width.
max_iterint1000Maximum iterations.
tolfloat1e-4Convergence tolerance.
Returns

JSON with predictions.

Algorithm

$$\min_{w,b}\frac{1}{2}|w|^2 + C\sum_i \max(0, |y_i - (w^Tx_i+b)| - \varepsilon)$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(400, 4)
y = X[:, 0] * 2 - X[:, 2] + np.random.randn(400) * 0.5
svr = sp.LinearSVR(C=1.0, epsilon=0.1)
svr.fit(X, y)
print(svr.score(X, y))

Référence API

Nom de fonction JSON

ml_linear_svr — alias : linear_svr

Classe Python
sp.LinearSvr(C=1.0, epsilon=0.1, max_iter=1000, tol=1e-4)
Paramètres du constructeur
ParamètreTypeDéfautDescription
Cfloat1.0Paramètre de régularisation.
epsilonfloat0.1Largeur du tube epsilon.
max_iterint1000Nombre maximum d'itérations.
tolfloat1e-4Tolérance de convergence.
Retourne

JSON avec predictions.

Algorithme

$$\min_{w,b}\frac{1}{2}|w|^2 + C\sum_i \max(0, |y_i - (w^Tx_i+b)| - \varepsilon)$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(400, 4)
y = X[:, 0] * 2 - X[:, 2] + np.random.randn(400) * 0.5
svr = sp.LinearSVR(C=1.0, epsilon=0.1)
svr.fit(X, y)
print(svr.score(X, y))

Preprocessing

EN — Feature scaling and transformation utilities.

FR — Utilitaires de mise à l'échelle et de transformation des features.

Contents

StandardScaler

Transformer sklearn-compatible 🔧 Preprocessing

StandardScaler — zero-mean unit-variance standardisation. / StandardScaler — standardisation à moyenne nulle et variance unitaire.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(200, 4) * [3, 0.5, 10, 1]
scaler = sp.StandardScaler()
scaler.fit(X)
Xt = scaler.transform(X)
print(Xt.mean(0), Xt.std(0))
💡
EN — Drop-in replacement: sp.StandardScaler has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_standard_scaler — aliases: standard_scaler, standardize

Python class
sp.StandardScaler()
Constructor Parameters

No constructor parameters.

Returns

JSON with transformed matrix.

Algorithm

$$x' = \frac{x - \mu}{\sigma}$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(200, 4) * [3, 0.5, 10, 1]
scaler = sp.StandardScaler()
scaler.fit(X)
Xt = scaler.transform(X)
print(Xt.mean(0), Xt.std(0))

Référence API

Nom de fonction JSON

ml_standard_scaler — alias : standard_scaler, standardize

Classe Python
sp.StandardScaler()
Paramètres du constructeur

Aucun paramètre de constructeur.

Retourne

JSON avec matrice transformed.

Algorithme

$$x' = \frac{x - \mu}{\sigma}$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(200, 4) * [3, 0.5, 10, 1]
scaler = sp.StandardScaler()
scaler.fit(X)
Xt = scaler.transform(X)
print(Xt.mean(0), Xt.std(0))

MinmaxScaler

Transformer sklearn-compatible 🔧 Preprocessing

MinMaxScaler — scale features to [0, 1] range. / MinMaxScaler — mise à l'échelle des features dans l'intervalle [0, 1].

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(200, 3) * 100
scaler = sp.MinMaxScaler()
Xt = scaler.fit_transform(X)
print(Xt.min(), Xt.max())
💡
EN — Drop-in replacement: sp.MinmaxScaler has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_minmax_scaler — aliases: minmax_scaler, min_max_scaler

Python class
sp.MinmaxScaler()
Constructor Parameters

No constructor parameters.

Returns

JSON with transformed matrix.

Algorithm

$$x' = \frac{x - x_{\min}}{x_{\max} - x_{\min}}$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(200, 3) * 100
scaler = sp.MinMaxScaler()
Xt = scaler.fit_transform(X)
print(Xt.min(), Xt.max())

Référence API

Nom de fonction JSON

ml_minmax_scaler — alias : minmax_scaler, min_max_scaler

Classe Python
sp.MinmaxScaler()
Paramètres du constructeur

Aucun paramètre de constructeur.

Retourne

JSON avec matrice transformed.

Algorithme

$$x' = \frac{x - x_{\min}}{x_{\max} - x_{\min}}$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(200, 3) * 100
scaler = sp.MinMaxScaler()
Xt = scaler.fit_transform(X)
print(Xt.min(), Xt.max())

RobustScaler

Transformer sklearn-compatible 🔧 Preprocessing

RobustScaler — scale using median and IQR, robust to outliers. / RobustScaler — mise à l'échelle par médiane et IQR, robuste aux valeurs aberrantes.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(300, 4)
X[0, :] = 100
scaler = sp.RobustScaler()
Xt = scaler.fit_transform(X)
print(Xt.mean(0))
💡
EN — Drop-in replacement: sp.RobustScaler has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_robust_scaler — aliases: robust_scaler

Python class
sp.RobustScaler()
Constructor Parameters

No constructor parameters.

Returns

JSON with transformed matrix.

Algorithm

$$x' = \frac{x - \text{median}}{\text{IQR}}$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(300, 4)
X[0, :] = 100
scaler = sp.RobustScaler()
Xt = scaler.fit_transform(X)
print(Xt.mean(0))

Référence API

Nom de fonction JSON

ml_robust_scaler — alias : robust_scaler

Classe Python
sp.RobustScaler()
Paramètres du constructeur

Aucun paramètre de constructeur.

Retourne

JSON avec matrice transformed.

Algorithme

$$x' = \frac{x - \text{médiane}}{\text{IQR}}$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(300, 4)
X[0, :] = 100
scaler = sp.RobustScaler()
Xt = scaler.fit_transform(X)
print(Xt.mean(0))

FitTransform

Transformer sklearn-compatible 🔧 Preprocessing

Unified fit_transform — dispatches to StandardScaler/MinMaxScaler/RobustScaler by name. / fit_transform unifié — dispatche vers StandardScaler/MinMaxScaler/RobustScaler par nom.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
import json
X = np.random.randn(100, 3) * 5
res = json.loads(sp.ml_fit_transform(json.dumps({"X_train": X.tolist(), "scaler": "minmax"})))
💡
EN — Drop-in replacement: sp.FitTransform has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_fit_transform — aliases: fit_transform, preprocess

Python class
sp.FitTransform(scaler=standard)
Constructor Parameters
ParameterTypeDefaultDescription
scalerstrstandardScaler type: `standard`, `minmax`, `robust`.
Returns

JSON with transformed matrix.

Example
import seraplot as sp, numpy as np
import json
X = np.random.randn(100, 3) * 5
res = json.loads(sp.ml_fit_transform(json.dumps({"X_train": X.tolist(), "scaler": "minmax"})))

Référence API

Nom de fonction JSON

ml_fit_transform — alias : fit_transform, preprocess

Classe Python
sp.FitTransform(scaler=standard)
Paramètres du constructeur
ParamètreTypeDéfautDescription
scalerstrstandardType de scaler : `standard`, `minmax`, `robust`.
Retourne

JSON avec matrice transformed.

Exemple
import seraplot as sp, numpy as np
import json
X = np.random.randn(100, 3) * 5
res = json.loads(sp.ml_fit_transform(json.dumps({"X_train": X.tolist(), "scaler": "minmax"})))

Decomposition

EN — Dimensionality reduction via matrix factorisation.

FR — Réduction de dimensionnalité par factorisation matricielle.

Contents

Pca

Transformer sklearn-compatible 🔬 Decomposition

PCA — Principal Component Analysis via truncated SVD. / PCA — Analyse en Composantes Principales via SVD tronquée.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(300, 10)
pca = sp.PCA(n_components=3)
pca.fit(X)
Xt = pca.transform(X)
print(Xt.shape, pca.explained_variance_ratio_)
💡
EN — Drop-in replacement: sp.Pca has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_pca — aliases: pca

Python class
sp.Pca(n_components=2)
Constructor Parameters
ParameterTypeDefaultDescription
n_componentsint2Number of principal components.
Returns

JSON with transformed (n×k matrix), explained_variance_ratio.

Algorithm

$$X_{\text{proj}} = X W_k, \quad W_k = \text{top-}k\text{ right singular vectors of } \tilde{X}$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(300, 10)
pca = sp.PCA(n_components=3)
pca.fit(X)
Xt = pca.transform(X)
print(Xt.shape, pca.explained_variance_ratio_)

Référence API

Nom de fonction JSON

ml_pca — alias : pca

Classe Python
sp.Pca(n_components=2)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_componentsint2Nombre de composantes principales.
Retourne

JSON avec transformed (matrice n×k), explained_variance_ratio.

Algorithme

$$X_{\text{proj}} = X W_k, \quad W_k = k\text{ premiers vecteurs singuliers droits de } \tilde{X}$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(300, 10)
pca = sp.PCA(n_components=3)
pca.fit(X)
Xt = pca.transform(X)
print(Xt.shape, pca.explained_variance_ratio_)

TruncatedSvd

Transformer sklearn-compatible 🔬 Decomposition

TruncatedSVD — truncated Singular Value Decomposition (no centering, sparse-friendly). / TruncatedSVD — Décomposition en Valeurs Singulières tronquée (sans centrage, compatible sparse).

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.abs(np.random.randn(200, 15))
svd = sp.TruncatedSVD(n_components=5)
svd.fit(X)
Xt = svd.transform(X)
print(Xt.shape)
💡
EN — Drop-in replacement: sp.TruncatedSvd has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_truncated_svd — aliases: truncated_svd

Python class
sp.TruncatedSvd(n_components=2)
Constructor Parameters
ParameterTypeDefaultDescription
n_componentsint2Number of components to keep.
Returns

JSON with transformed, explained_variance_ratio.

Algorithm

$$X \approx U_k \Sigma_k V_k^T$$

Example
import seraplot as sp, numpy as np
X = np.abs(np.random.randn(200, 15))
svd = sp.TruncatedSVD(n_components=5)
svd.fit(X)
Xt = svd.transform(X)
print(Xt.shape)

Référence API

Nom de fonction JSON

ml_truncated_svd — alias : truncated_svd

Classe Python
sp.TruncatedSvd(n_components=2)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_componentsint2Nombre de composantes à conserver.
Retourne

JSON avec transformed, explained_variance_ratio.

Algorithme

$$X \approx U_k \Sigma_k V_k^T$$

Exemple
import seraplot as sp, numpy as np
X = np.abs(np.random.randn(200, 15))
svd = sp.TruncatedSVD(n_components=5)
svd.fit(X)
Xt = svd.transform(X)
print(Xt.shape)

Model Selection

EN — Cross-validation, hyperparameter tuning, and feature importance.

FR — Validation croisée, optimisation des hyperparamètres et importance des features.

Contents

GridSearchCv

Utility sklearn-compatible ⚙️ Model Selection

Grid search with cross-validation — exhaustive hyperparameter search. / Recherche en grille avec validation croisée — recherche exhaustive d'hyperparamètres.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, json, numpy as np
X = np.random.randn(200, 5)
y = X[:, 0] * 2 + np.random.randn(200) * 0.3
payload = {"X_train": X.tolist(), "y_train": y.tolist(), "param_grid": {"alpha": [0.1, 1.0, 10.0]}}
res = json.loads(sp.ml_grid_search_cv(json.dumps(payload)))
print(res["best_params"], res["best_score"])
💡
EN — Drop-in replacement: sp.GridSearchCv has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_grid_search_cv — aliases: grid_search_cv

Python class
sp.GridSearchCv(param_grid={}, n_splits=5, scoring=auto)
Constructor Parameters
ParameterTypeDefaultDescription
param_griddict{}Hyperparameter grid to search.
n_splitsint5Number of CV folds.
scoringstrautoScoring metric.
Returns

JSON with best_params, best_score, cv_results.

Example
import seraplot as sp, json, numpy as np
X = np.random.randn(200, 5)
y = X[:, 0] * 2 + np.random.randn(200) * 0.3
payload = {"X_train": X.tolist(), "y_train": y.tolist(), "param_grid": {"alpha": [0.1, 1.0, 10.0]}}
res = json.loads(sp.ml_grid_search_cv(json.dumps(payload)))
print(res["best_params"], res["best_score"])

Référence API

Nom de fonction JSON

ml_grid_search_cv — alias : grid_search_cv

Classe Python
sp.GridSearchCv(param_grid={}, n_splits=5, scoring=auto)
Paramètres du constructeur
ParamètreTypeDéfautDescription
param_griddict{}Grille d'hyperparamètres à explorer.
n_splitsint5Nombre de plis CV.
scoringstrautoMétrique de scoring.
Retourne

JSON avec best_params, best_score, cv_results.

Exemple
import seraplot as sp, json, numpy as np
X = np.random.randn(200, 5)
y = X[:, 0] * 2 + np.random.randn(200) * 0.3
payload = {"X_train": X.tolist(), "y_train": y.tolist(), "param_grid": {"alpha": [0.1, 1.0, 10.0]}}
res = json.loads(sp.ml_grid_search_cv(json.dumps(payload)))
print(res["best_params"], res["best_score"])

KfoldSplit

Utility sklearn-compatible ⚙️ Model Selection

K-Fold split — returns train/test index arrays for k-fold cross-validation. / Division K-Fold — retourne les tableaux d'indices train/test pour la validation croisée k-fold.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, json, numpy as np
X = np.random.randn(100, 4)
res = json.loads(sp.ml_kfold_split(json.dumps({"X_train": X.tolist(), "n_splits": 5})))
print(len(res["folds"]))
💡
EN — Drop-in replacement: sp.KfoldSplit has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_kfold_split — aliases: kfold_split

Python class
sp.KfoldSplit(n_splits=5, stratified=false, seed=42)
Constructor Parameters
ParameterTypeDefaultDescription
n_splitsint5Number of folds.
stratifiedboolfalseUse stratified splits (requires y_train).
seedint42Random seed.
Returns

JSON with folds array, each fold has train_indices, test_indices.

Example
import seraplot as sp, json, numpy as np
X = np.random.randn(100, 4)
res = json.loads(sp.ml_kfold_split(json.dumps({"X_train": X.tolist(), "n_splits": 5})))
print(len(res["folds"]))

Référence API

Nom de fonction JSON

ml_kfold_split — alias : kfold_split

Classe Python
sp.KfoldSplit(n_splits=5, stratified=false, seed=42)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_splitsint5Nombre de plis.
stratifiedboolfalseUtiliser des splits stratifiés (nécessite y_train).
seedint42Graine aléatoire.
Retourne

JSON avec tableau folds, chaque pli a train_indices, test_indices.

Exemple
import seraplot as sp, json, numpy as np
X = np.random.randn(100, 4)
res = json.loads(sp.ml_kfold_split(json.dumps({"X_train": X.tolist(), "n_splits": 5})))
print(len(res["folds"]))

CrossValScore

Utility sklearn-compatible ⚙️ Model Selection

Cross-validation score — evaluates model performance across k folds. / Score de validation croisée — évalue la performance du modèle sur k plis.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, json, numpy as np
X = np.random.randn(200, 5)
y = X @ [1, -1, 0.5, 0, 1] + np.random.randn(200) * 0.3
payload = {"X_train": X.tolist(), "y_train": y.tolist(), "model": "ridge", "n_splits": 5}
res = json.loads(sp.ml_cross_val_score(json.dumps(payload)))
print(res["scores"], res["mean_score"])
💡
EN — Drop-in replacement: sp.CrossValScore has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_cross_val_score — aliases: cross_val_score

Python class
sp.CrossValScore(model=ridge, n_splits=5, scoring=auto)
Constructor Parameters
ParameterTypeDefaultDescription
modelstrridgeModel name for evaluation.
n_splitsint5Number of folds.
scoringstrautoScore metric.
Returns

JSON with scores array and mean_score.

Algorithm

$$\text{CV}(k) = \frac{1}{k}\sum_{i=1}^{k} s_i$$

Example
import seraplot as sp, json, numpy as np
X = np.random.randn(200, 5)
y = X @ [1, -1, 0.5, 0, 1] + np.random.randn(200) * 0.3
payload = {"X_train": X.tolist(), "y_train": y.tolist(), "model": "ridge", "n_splits": 5}
res = json.loads(sp.ml_cross_val_score(json.dumps(payload)))
print(res["scores"], res["mean_score"])

Référence API

Nom de fonction JSON

ml_cross_val_score — alias : cross_val_score

Classe Python
sp.CrossValScore(model=ridge, n_splits=5, scoring=auto)
Paramètres du constructeur
ParamètreTypeDéfautDescription
modelstrridgeNom du modèle à évaluer.
n_splitsint5Nombre de plis.
scoringstrautoMétrique de score.
Retourne

JSON avec tableau scores et mean_score.

Algorithme

$$\text{CV}(k) = \frac{1}{k}\sum_{i=1}^{k} s_i$$

Exemple
import seraplot as sp, json, numpy as np
X = np.random.randn(200, 5)
y = X @ [1, -1, 0.5, 0, 1] + np.random.randn(200) * 0.3
payload = {"X_train": X.tolist(), "y_train": y.tolist(), "model": "ridge", "n_splits": 5}
res = json.loads(sp.ml_cross_val_score(json.dumps(payload)))
print(res["scores"], res["mean_score"])

PermutationImportance

Utility sklearn-compatible ⚙️ Model Selection

Permutation importance — feature importance by permuting each column and measuring score drop. / Importance par permutation — importance des features en permutant chaque colonne et mesurant la baisse de score.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, json, numpy as np
X = np.random.randn(200, 5)
y = X @ [2, -1, 0, 0.5, 1.2] + np.random.randn(200) * 0.3
model = sp.Ridge(alpha=0.5)
model.fit(X, y)
imp = sp.permutation_importance(model, X, y, n_repeats=5)
print(imp.importances_mean_)
💡
EN — Drop-in replacement: sp.PermutationImportance has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_permutation_importance — aliases: permutation_importance

Python class
sp.PermutationImportance(n_repeats=10, scoring=auto)
Constructor Parameters
ParameterTypeDefaultDescription
n_repeatsint10Number of permutations per feature.
scoringstrautoScoring metric: auto-detects cls/reg.
Returns

JSON with importances_mean, importances_std per feature.

Algorithm

$$\text{imp}j = \bar{s} - \frac{1}{K}\sum{k=1}^{K} s(\text{perm}_k(X_j))$$

Example
import seraplot as sp, json, numpy as np
X = np.random.randn(200, 5)
y = X @ [2, -1, 0, 0.5, 1.2] + np.random.randn(200) * 0.3
model = sp.Ridge(alpha=0.5)
model.fit(X, y)
imp = sp.permutation_importance(model, X, y, n_repeats=5)
print(imp.importances_mean_)

Référence API

Nom de fonction JSON

ml_permutation_importance — alias : permutation_importance

Classe Python
sp.PermutationImportance(n_repeats=10, scoring=auto)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_repeatsint10Nombre de permutations par feature.
scoringstrautoMétrique de scoring : auto-détecte cls/reg.
Retourne

JSON avec importances_mean, importances_std par feature.

Algorithme

$$\text{imp}j = \bar{s} - \frac{1}{K}\sum{k=1}^{K} s(\text{perm}_k(X_j))$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(200, 5)
y = X @ [2, -1, 0, 0.5, 1.2] + np.random.randn(200) * 0.3
model = sp.Ridge(alpha=0.5)
model.fit(X, y)
imp = sp.permutation_importance(model, X, y, n_repeats=5)
print(imp.importances_mean_)

IsolationForest

Detector sklearn-compatible 🚨 Anomaly Detection

IsolationForest — anomaly detection via random partitioning trees. / IsolationForest — détection d'anomalies via arbres de partition aléatoire.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, numpy as np
X = np.random.randn(300, 4)
X[0] = [10, 10, 10, 10]
iso = sp.IsolationForest(n_estimators=100, contamination=0.05)
iso.fit(X)
print(iso.predict(X[:5]))
💡
EN — Drop-in replacement: sp.IsolationForest has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_isolation_forest — aliases: isolation_forest

Python class
sp.IsolationForest(n_estimators=100, max_samples=256, contamination=0.1, seed=42)
Constructor Parameters
ParameterTypeDefaultDescription
n_estimatorsint100Number of isolation trees.
max_samplesint256Max samples per tree.
contaminationfloat0.1Expected fraction of outliers.
seedint42Random seed.
Returns

JSON with labels (1 = inlier, −1 = outlier), scores.

Algorithm

$$s(x) = 2^{-E[h(x)]/c(n)}, \quad c(n) = 2H_{n-1} - \frac{2(n-1)}{n}$$

Example
import seraplot as sp, numpy as np
X = np.random.randn(300, 4)
X[0] = [10, 10, 10, 10]
iso = sp.IsolationForest(n_estimators=100, contamination=0.05)
iso.fit(X)
print(iso.predict(X[:5]))

Référence API

Nom de fonction JSON

ml_isolation_forest — alias : isolation_forest

Classe Python
sp.IsolationForest(n_estimators=100, max_samples=256, contamination=0.1, seed=42)
Paramètres du constructeur
ParamètreTypeDéfautDescription
n_estimatorsint100Nombre d'arbres d'isolation.
max_samplesint256Max échantillons par arbre.
contaminationfloat0.1Fraction attendue de valeurs aberrantes.
seedint42Graine aléatoire.
Retourne

JSON avec labels (1 = normal, −1 = anomalie), scores.

Algorithme

$$s(x) = 2^{-E[h(x)]/c(n)}, \quad c(n) = 2H_{n-1} - \frac{2(n-1)}{n}$$

Exemple
import seraplot as sp, numpy as np
X = np.random.randn(300, 4)
X[0] = [10, 10, 10, 10]
iso = sp.IsolationForest(n_estimators=100, contamination=0.05)
iso.fit(X)
print(iso.predict(X[:5]))

MetricScore

Utility sklearn-compatible 📏 Metrics

Compute a named metric score (accuracy, r2, f1, etc.) from predictions. / Calcule un score de métrique nommée (accuracy, r2, f1, etc.) à partir des prédictions.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, json
payload = {"y_true": [0,1,1,0,1], "y_pred": [0,1,0,0,1], "metric": "accuracy"}
res = json.loads(sp.ml_metric_score(json.dumps(payload)))
print(res["score"])
💡
EN — Drop-in replacement: sp.MetricScore has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_metric_score — aliases: metric_score

Python class
sp.MetricScore(metric=accuracy)
Constructor Parameters
ParameterTypeDefaultDescription
metricstraccuracyMetric name: `accuracy`, `r2`, `f1`, `precision`, `recall`, `mse`, `mae`.
Returns

JSON with score.

Example
import seraplot as sp, json
payload = {"y_true": [0,1,1,0,1], "y_pred": [0,1,0,0,1], "metric": "accuracy"}
res = json.loads(sp.ml_metric_score(json.dumps(payload)))
print(res["score"])

Référence API

Nom de fonction JSON

ml_metric_score — alias : metric_score

Classe Python
sp.MetricScore(metric=accuracy)
Paramètres du constructeur
ParamètreTypeDéfautDescription
metricstraccuracyNom de la métrique : `accuracy`, `r2`, `f1`, `precision`, `recall`, `mse`, `mae`.
Retourne

JSON avec score.

Exemple
import seraplot as sp, json
payload = {"y_true": [0,1,1,0,1], "y_pred": [0,1,0,0,1], "metric": "accuracy"}
res = json.loads(sp.ml_metric_score(json.dumps(payload)))
print(res["score"])

MetricCurve

Utility sklearn-compatible 📏 Metrics

Compute a metric curve (ROC, PR, confusion matrix) from predictions. / Calcule une courbe de métrique (ROC, PR, matrice de confusion) à partir des prédictions.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, json
import numpy as np
y_true = (np.random.randn(100) > 0).astype(int).tolist()
y_score = np.random.rand(100).tolist()
res = json.loads(sp.ml_metric_curve(json.dumps({"y_true": y_true, "y_score": y_score, "curve": "roc"})))
💡
EN — Drop-in replacement: sp.MetricCurve has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_metric_curve — aliases: metric_curve

Python class
sp.MetricCurve(curve=roc)
Constructor Parameters
ParameterTypeDefaultDescription
curvestrrocCurve type: `roc`, `pr`, `confusion`.
Returns

JSON with curve data points.

Example
import seraplot as sp, json
import numpy as np
y_true = (np.random.randn(100) > 0).astype(int).tolist()
y_score = np.random.rand(100).tolist()
res = json.loads(sp.ml_metric_curve(json.dumps({"y_true": y_true, "y_score": y_score, "curve": "roc"})))

Référence API

Nom de fonction JSON

ml_metric_curve — alias : metric_curve

Classe Python
sp.MetricCurve(curve=roc)
Paramètres du constructeur
ParamètreTypeDéfautDescription
curvestrrocType de courbe : `roc`, `pr`, `confusion`.
Retourne

JSON avec les points de la courbe.

Exemple
import seraplot as sp, json
import numpy as np
y_true = (np.random.randn(100) > 0).astype(int).tolist()
y_score = np.random.rand(100).tolist()
res = json.loads(sp.ml_metric_curve(json.dumps({"y_true": y_true, "y_score": y_score, "curve": "roc"})))

SaveModel

Utility sklearn-compatible 📦 Registry

Save model to the in-memory registry with name, version, and metadata. / Sauvegarder le modèle dans le registre en mémoire avec nom, version et métadonnées.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, json, numpy as np
X = np.random.randn(100, 3)
y = X[:, 0] * 2 + np.random.randn(100) * 0.3
model = sp.Ridge(alpha=0.5)
model.fit(X, y)
res = json.loads(sp.ml_save_model(json.dumps({"name": "my_ridge", "kind": "ridge"})))
print(res["version"])
💡
EN — Drop-in replacement: sp.SaveModel has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_save_model — aliases: save_model

Python class
sp.SaveModel(name=required, kind=required)
Constructor Parameters
ParameterTypeDefaultDescription
namestrrequiredModel name.
kindstrrequiredModel type (e.g. `ridge`, `random_forest`).
Returns

JSON with saved ModelRecord (id, name, version, created_at).

Example
import seraplot as sp, json, numpy as np
X = np.random.randn(100, 3)
y = X[:, 0] * 2 + np.random.randn(100) * 0.3
model = sp.Ridge(alpha=0.5)
model.fit(X, y)
res = json.loads(sp.ml_save_model(json.dumps({"name": "my_ridge", "kind": "ridge"})))
print(res["version"])

Référence API

Nom de fonction JSON

ml_save_model — alias : save_model

Classe Python
sp.SaveModel(name=required, kind=required)
Paramètres du constructeur
ParamètreTypeDéfautDescription
namestrrequiredNom du modèle.
kindstrrequiredType de modèle (ex. `ridge`, `random_forest`).
Retourne

JSON avec ModelRecord sauvegardé (id, name, version, created_at).

Exemple
import seraplot as sp, json, numpy as np
X = np.random.randn(100, 3)
y = X[:, 0] * 2 + np.random.randn(100) * 0.3
model = sp.Ridge(alpha=0.5)
model.fit(X, y)
res = json.loads(sp.ml_save_model(json.dumps({"name": "my_ridge", "kind": "ridge"})))
print(res["version"])

LoadModel

Utility sklearn-compatible 📦 Registry

Load a model from the registry by name and optional version. / Charger un modèle depuis le registre par nom et version optionnelle.

⚡ Rust-native ✓ sklearn parity
Quick start — Python
import seraplot as sp, json
res = json.loads(sp.ml_load_model(json.dumps({"name": "my_ridge"})))
print(res)
💡
EN — Drop-in replacement: sp.LoadModel has the same API as sklearn.
FR — Remplacement direct : même API que sklearn, changez l'import.

API Reference

JSON function name

ml_load_model — aliases: load_model

Python class
sp.LoadModel(name=required, version=null)
Constructor Parameters
ParameterTypeDefaultDescription
namestrrequiredModel name.
versionintnullVersion to load (latest if omitted).
Returns

JSON with ModelRecord or null if not found.

Example
import seraplot as sp, json
res = json.loads(sp.ml_load_model(json.dumps({"name": "my_ridge"})))
print(res)

Référence API

Nom de fonction JSON

ml_load_model — alias : load_model

Classe Python
sp.LoadModel(name=required, version=null)
Paramètres du constructeur
ParamètreTypeDéfautDescription
namestrrequiredNom du modèle.
versionintnullVersion à charger (dernière si omis).
Retourne

JSON avec ModelRecord ou null si non trouvé.

Exemple
import seraplot as sp, json
res = json.loads(sp.ml_load_model(json.dumps({"name": "my_ridge"})))
print(res)

Telemetry

Telemetry reference

Runtime metrics, consent, and the real implementation.

Telemetry is a small opt-in subsystem. It records coarse runtime metrics, writes failed sends locally, and dispatches in the background only when a token is configured.

OffDefault state
Consent file~/.seraplot
JSONLLocal queue
Env tokenNo hardcoded secret

The implementation is intentionally boring: consent gates collection, events are serialized as JSON, and failed sends stay in a local queue. The GitHub dispatch token is read from SERAPLOT_GITHUB_TOKEN or a local git-ignored .env file.

The payload is built from runtime metadata and optional call-site context. It does not include user files, raw values, credentials, model weights, or personally identifying account data.

Collected Fields
MetricTypeDescriptionExample
tsCOREtimestampUnix timestamp for the event.1746615600
methodCOREstringFunction or method name."scatter"
duration_msCOREfloatExecution time rounded to milliseconds.0.113
versionCOREstringInstalled SeraPlot version."2.7.10"
os, archCOREstringOperating system and CPU architecture."windows", "x86_64"
cpu_count, ram_gbCOREnumberBasic system capacity information.16, 32.0
data_countOPTintegerNumber of records processed, when available.1000000
input_shape, output_shapeOPTstringData dimensions supplied by the call site."1000x256"
algorithmOPTstringAlgorithm name for ML-related events."KMeans"
Privacy And Flow
Never collected
  • No user identity, credentials, or account data.
  • No file names, file contents, or raw values.
  • No model weights, parameters, or samples.
  • No IP address or geolocation in the payload.
Runtime flow
1
CaptureMethod, duration, version, and system summary are recorded after a call.
2
QueueThe event is appended to telemetry.jsonl.
3
DispatchA background thread sends the payload if a token exists.
4
FlushSuccessfully sent pending events are cleared.
API
Enable, disable, inspect
import seraplot as sp

sp.telemetry_consent(enabled=True) # opt in sp.telemetry_consent(enabled=False) # opt out

metrics = sp.get_metrics_summary() print(metrics)

Reference telemetry

Metriques runtime, consentement et implementation reelle.

La telemetry est un petit sous-systeme opt-in. Elle enregistre des metriques runtime generales, conserve les envois echoues en local et dispatch en arriere-plan seulement si un token est configure.

OffEtat par defaut
Consentement~/.seraplot
JSONLQueue locale
Token envPas de secret hardcode

L'implementation reste volontairement simple : le consentement controle la collecte, les evenements sont serialises en JSON, et les envois echoues restent dans une queue locale. Le token GitHub dispatch est lu depuis SERAPLOT_GITHUB_TOKEN ou depuis un fichier local .env ignore par git.

Le payload contient des metadonnees runtime et du contexte optionnel fourni par le call site. Il n'inclut pas les fichiers utilisateur, les valeurs brutes, les credentials, les poids de modele ou les donnees de compte identifiantes.

Champs Collectes
MetriqueTypeDescriptionExemple
tsCOREtimestampHorodatage Unix de l'evenement.1746615600
methodCOREstringNom de la fonction ou methode."scatter"
duration_msCOREfloatTemps d'execution arrondi en millisecondes.0.113
versionCOREstringVersion de SeraPlot installee."2.7.10"
os, archCOREstringSysteme et architecture CPU."windows", "x86_64"
cpu_count, ram_gbCOREnumberInformations systeme generales.16, 32.0
data_countOPTintegerNombre d'enregistrements traites si disponible.1000000
input_shape, output_shapeOPTstringDimensions fournies par le call site."1000x256"
algorithmOPTstringNom d'algorithme pour les evenements ML."KMeans"
Confidentialite Et Flux
Jamais collecte
  • Non identite utilisateur, credentials ou donnees de compte.
  • Non noms de fichiers, contenus ou valeurs brutes.
  • Non poids de modele, parametres ou samples.
  • Non adresse IP ou geolocalisation dans le payload.
Flux runtime
1
CaptureMethode, duree, version et resume systeme sont enregistres apres un appel.
2
QueueL'evenement est ajoute a telemetry.jsonl.
3
DispatchUn thread en arriere-plan envoie le payload si un token existe.
4
FlushLes evenements envoyes avec succes sont supprimes de la queue.
API
Activer, desactiver, inspecter
import seraplot as sp

sp.telemetry_consent(enabled=True) # activer sp.telemetry_consent(enabled=False) # desactiver

metrics = sp.get_metrics_summary() print(metrics)

telemetry.rs
telemetry.rs
real src/telemetry.rs
#![allow(unused)]
fn main() {
use std::collections::HashMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

#[cfg(not(target_arch = "wasm32"))]
const GITHUB_DISPATCH_URL: &str = "https://api.github.com/repos/feur25/seraplot/dispatches";
#[cfg(not(target_arch = "wasm32"))]
const GITHUB_TOKEN_ENV: &str = "SERAPLOT_GITHUB_TOKEN";

const CONSENT_FILE: &str = "consent.json";
const TELEMETRY_FILE: &str = "telemetry.jsonl";
const UNKNOWN: &str = "Unknown";

static PYTHON_VER: std::sync::OnceLock<String> = std::sync::OnceLock::new();
static SYS_INFO_CACHE: std::sync::OnceLock<serde_json::Value> = std::sync::OnceLock::new();
#[cfg(not(target_arch = "wasm32"))]
static GITHUB_TOKEN_CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();

pub fn set_python_version(v: &str) {
    let _ = PYTHON_VER.set(v.to_string());
}

#[derive(Clone, Debug)]
pub struct TelemetryEvent {
    pub method: String,
    pub duration_ms: f64,
    pub data_count: Option<u64>,
    pub data_size_mb: Option<f64>,
    pub input_shape: Option<String>,
    pub output_shape: Option<String>,
    pub algorithm: Option<String>,
}

#[derive(Clone, Debug)]
pub struct TelemetryEventBuilder {
    event: TelemetryEvent,
}

impl TelemetryEvent {
    pub fn new(method: &str, duration_ms: f64) -> Self {
        Self::builder(method, duration_ms).build()
    }

    pub fn builder(method: &str, duration_ms: f64) -> TelemetryEventBuilder {
        TelemetryEventBuilder {
            event: Self {
                method: method.to_string(),
                duration_ms,
                data_count: None,
                data_size_mb: None,
                input_shape: None,
                output_shape: None,
                algorithm: None,
            },
        }
    }

    pub fn with_data(mut self, count: u64, size_mb: f64) -> Self {
        self.data_count = Some(count);
        self.data_size_mb = Some(size_mb);
        self
    }

    pub fn with_count(mut self, count: u64) -> Self {
        self.data_count = Some(count);
        self
    }

    pub fn with_shapes(mut self, input: &str, output: &str) -> Self {
        self.input_shape = Some(input.to_string());
        self.output_shape = Some(output.to_string());
        self
    }

    pub fn with_algorithm(mut self, algo: &str) -> Self {
        self.algorithm = Some(algo.to_string());
        self
    }
}

impl TelemetryEventBuilder {
    pub fn data(mut self, count: u64, size_mb: f64) -> Self {
        self.event.data_count = Some(count);
        self.event.data_size_mb = Some(size_mb);
        self
    }

    pub fn count(mut self, count: u64) -> Self {
        self.event.data_count = Some(count);
        self
    }

    pub fn shapes(mut self, input: &str, output: &str) -> Self {
        self.event.input_shape = Some(input.to_string());
        self.event.output_shape = Some(output.to_string());
        self
    }

    pub fn algorithm(mut self, algo: &str) -> Self {
        self.event.algorithm = Some(algo.to_string());
        self
    }

    pub fn build(self) -> TelemetryEvent {
        self.event
    }
}

fn round_to(value: f64, scale: f64) -> f64 {
    (value * scale).round() / scale
}

fn round2(value: f64) -> f64 {
    round_to(value, 100.0)
}

fn round3(value: f64) -> f64 {
    round_to(value, 1000.0)
}

fn seraplot_dir() -> PathBuf {
    std::env::var("USERPROFILE")
        .or_else(|_| std::env::var("HOME"))
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("."))
        .join(".seraplot")
}

fn telemetry_path() -> PathBuf {
    seraplot_dir().join(TELEMETRY_FILE)
}

fn consent_path() -> PathBuf {
    seraplot_dir().join(CONSENT_FILE)
}

#[cfg(not(target_arch = "wasm32"))]
fn parse_bytes(s: &str) -> f64 {
    s.chars()
        .filter(|c| c.is_ascii_digit())
        .collect::<String>()
        .parse::<f64>()
        .unwrap_or(0.0)
}

#[cfg(target_os = "windows")]
fn platform_system_info() -> (f64, f64, String) {
    let ps = r#"try{$c=Get-CimInstance Win32_ComputerSystem;$o=Get-CimInstance Win32_OperatingSystem;$p=Get-CimInstance Win32_Processor|Select-Object -First 1;Write-Output "$($c.TotalPhysicalMemory)|$($o.FreePhysicalMemory)|$($p.Name)"}catch{Write-Output '0|0|Unknown'}"#;
    let out = std::process::Command::new("powershell")
        .args(["-NoProfile", "-NonInteractive", "-Command", ps])
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .unwrap_or_default();
    let parts: Vec<&str> = out.trim().splitn(3, '|').collect();
    let ram_gb = parse_bytes(parts.first().unwrap_or(&"0")) / 1024.0_f64.powi(3);
    let available_ram_gb = parse_bytes(parts.get(1).unwrap_or(&"0")) / (1024.0 * 1024.0);
    let cpu_brand = parts
        .get(2)
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| UNKNOWN.to_string());
    (ram_gb, available_ram_gb, cpu_brand)
}

#[cfg(target_os = "linux")]
fn meminfo_gb(text: &str, key: &str) -> f64 {
    text.lines()
        .find(|line| line.starts_with(key))
        .and_then(|line| line.split_whitespace().nth(1))
        .and_then(|kb| kb.parse::<f64>().ok())
        .map(|kb| kb / (1024.0 * 1024.0))
        .unwrap_or(0.0)
}

#[cfg(target_os = "linux")]
fn platform_system_info() -> (f64, f64, String) {
    let meminfo = std::fs::read_to_string("/proc/meminfo").unwrap_or_default();
    let ram_gb = meminfo_gb(&meminfo, "MemTotal:");
    let available_ram_gb = meminfo_gb(&meminfo, "MemAvailable:");
    let cpu_brand = std::fs::read_to_string("/proc/cpuinfo")
        .ok()
        .and_then(|text| {
            text.lines()
                .find(|line| line.starts_with("model name:"))
                .and_then(|line| line.split_once(':'))
                .map(|(_, brand)| brand.trim().to_string())
        })
        .filter(|brand| !brand.is_empty())
        .unwrap_or_else(|| UNKNOWN.to_string());
    (ram_gb, available_ram_gb, cpu_brand)
}

#[cfg(target_os = "macos")]
fn command_stdout(command: &str, args: &[&str]) -> Option<String> {
    std::process::Command::new(command)
        .args(args)
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
}

#[cfg(target_os = "macos")]
fn platform_system_info() -> (f64, f64, String) {
    let ram_gb = command_stdout("sysctl", &["-n", "hw.memsize"])
        .and_then(|s| s.trim().parse::<f64>().ok())
        .map(|bytes| bytes / 1024.0_f64.powi(3))
        .unwrap_or(0.0);
    let available_ram_gb = command_stdout("vm_stat", &[])
        .and_then(|text| {
            text.lines()
                .find(|line| line.contains("Pages free"))
                .and_then(|line| line.split_whitespace().nth(2))
                .and_then(|pages| pages.trim_end_matches('.').parse::<f64>().ok())
                .map(|pages| pages * 4096.0 / 1024.0_f64.powi(3))
        })
        .unwrap_or(0.0);
    let cpu_brand = command_stdout("sysctl", &["-n", "machdep.cpu.brand_string"])
        .map(|s| s.trim().to_string())
        .filter(|brand| !brand.is_empty())
        .unwrap_or_else(|| UNKNOWN.to_string());
    (ram_gb, available_ram_gb, cpu_brand)
}

#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
fn platform_system_info() -> (f64, f64, String) {
    (0.0, 0.0, UNKNOWN.to_string())
}

fn collect_system_info() -> serde_json::Value {
    let (ram_gb, available_ram_gb, cpu_brand) = platform_system_info();
    serde_json::json!({
        "os": std::env::consts::OS,
        "arch": std::env::consts::ARCH,
        "cpu_count": std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1),
        "ram_gb": round2(ram_gb),
        "available_ram_gb": round2(available_ram_gb),
        "cpu_brand": cpu_brand,
        "python_version": PYTHON_VER.get().cloned().unwrap_or_else(|| "unknown".to_string())
    })
}

fn sys_info() -> &'static serde_json::Value {
    SYS_INFO_CACHE.get_or_init(collect_system_info)
}

#[cfg(not(target_arch = "wasm32"))]
fn clean_token(value: &str) -> Option<String> {
    let token = value
        .trim()
        .trim_matches('"')
        .trim_matches('\'')
        .to_string();
    (!token.is_empty()).then_some(token)
}

#[cfg(not(target_arch = "wasm32"))]
fn dotenv_candidates() -> Vec<PathBuf> {
    let cwd_candidates = std::env::current_dir()
        .ok()
        .into_iter()
        .flat_map(|cwd| {
            cwd.ancestors()
                .take(6)
                .map(Path::to_path_buf)
                .collect::<Vec<_>>()
        })
        .map(|dir| dir.join(".env"));
    cwd_candidates
        .chain([seraplot_dir().join(".env")])
        .collect()
}

#[cfg(not(target_arch = "wasm32"))]
fn token_from_dotenv(path: &Path) -> Option<String> {
    std::fs::read_to_string(path).ok().and_then(|text| {
        text.lines().find_map(|line| {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                return None;
            }
            let (key, value) = line.split_once('=')?;
            (key.trim() == GITHUB_TOKEN_ENV)
                .then(|| clean_token(value))
                .flatten()
        })
    })
}

#[cfg(not(target_arch = "wasm32"))]
fn dotenv_token() -> Option<String> {
    dotenv_candidates()
        .iter()
        .find_map(|path| token_from_dotenv(path))
}

#[cfg(not(target_arch = "wasm32"))]
fn github_token() -> Option<&'static str> {
    GITHUB_TOKEN_CACHE
        .get_or_init(|| {
            std::env::var(GITHUB_TOKEN_ENV)
                .ok()
                .and_then(|value| clean_token(&value))
                .or_else(dotenv_token)
        })
        .as_deref()
}

fn github_dispatch_body(event: serde_json::Value) -> Option<String> {
    serde_json::to_string(&serde_json::json!({
        "event_type": "seraplot-telemetry",
        "client_payload": { "events": [event] }
    }))
    .ok()
}

fn try_send_event(event: serde_json::Value) -> bool {
    let Some(body) = github_dispatch_body(event) else {
        return false;
    };

    #[cfg(target_arch = "wasm32")]
    {
        let _ = body;
        false
    }

    #[cfg(not(target_arch = "wasm32"))]
    {
        let Some(token) = github_token() else {
            return false;
        };
        reqwest::blocking::Client::builder()
            .timeout(std::time::Duration::from_secs(5))
            .build()
            .ok()
            .and_then(|client| {
                client
                    .post(GITHUB_DISPATCH_URL)
                    .header("Authorization", format!("token {}", token))
                    .header("Accept", "application/vnd.github+json")
                    .header("Content-Type", "application/json")
                    .header("User-Agent", format!("seraplot/{}", crate::VERSION))
                    .body(body)
                    .send()
                    .ok()
            })
            .map(|response| response.status().as_u16() == 204)
            .unwrap_or(false)
    }
}

pub fn is_consent_given() -> bool {
    let path = consent_path();
    if !path.exists() {
        return false;
    }
    std::fs::read_to_string(path)
        .ok()
        .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
        .and_then(|value| value.get("enabled").and_then(|enabled| enabled.as_bool()))
        .unwrap_or(false)
}

pub fn set_consent(enabled: bool) {
    let dir = seraplot_dir();
    let payload = serde_json::json!({
        "enabled": enabled,
        "version": crate::VERSION
    });
    let _ = std::fs::create_dir_all(&dir);
    let _ = std::fs::write(dir.join(CONSENT_FILE), payload.to_string());
}

fn event_optional_fields(event: &TelemetryEvent) -> Vec<(&'static str, serde_json::Value)> {
    [
        event.data_count.map(|value| ("data_count", value.into())),
        event
            .data_size_mb
            .map(|value| ("data_size_mb", round2(value).into())),
        event
            .input_shape
            .as_ref()
            .map(|value| ("input_shape", value.clone().into())),
        event
            .output_shape
            .as_ref()
            .map(|value| ("output_shape", value.clone().into())),
        event
            .algorithm
            .as_ref()
            .map(|value| ("algorithm", value.clone().into())),
    ]
    .into_iter()
    .flatten()
    .collect()
}

fn build_event_json(event: &TelemetryEvent, ts: u64) -> serde_json::Value {
    let mut fields = serde_json::Map::from_iter([
        ("method".to_string(), event.method.clone().into()),
        ("duration_ms".to_string(), round3(event.duration_ms).into()),
        ("version".to_string(), crate::VERSION.into()),
        ("ts".to_string(), ts.into()),
    ]);

    if let Some(system) = sys_info().as_object() {
        fields.extend(
            system
                .iter()
                .map(|(key, value)| (key.clone(), value.clone())),
        );
    }

    fields.extend(
        event_optional_fields(event)
            .into_iter()
            .map(|(key, value)| (key.to_string(), value)),
    );

    serde_json::Value::Object(fields)
}

pub fn record(event: TelemetryEvent) {
    if !is_consent_given() {
        return;
    }

    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .unwrap_or(0);
    let event_json = build_event_json(&event, ts);

    if let Ok(mut file) = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(telemetry_path())
    {
        let _ = writeln!(file, "{}", event_json);
    }

    std::thread::spawn(move || {
        try_send_event(event_json);
    });
}

pub fn telemetry_file_path() -> String {
    telemetry_path().to_string_lossy().into_owned()
}

pub fn read_pending() -> Vec<serde_json::Value> {
    std::fs::read_to_string(telemetry_path())
        .ok()
        .map(|text| {
            text.lines()
                .filter_map(|line| serde_json::from_str(line).ok())
                .collect()
        })
        .unwrap_or_default()
}

pub fn clear_pending() {
    let _ = std::fs::write(telemetry_path(), b"");
}

fn endpoint_body(events: &[serde_json::Value], token: &str) -> Result<String, String> {
    let system = get_metrics_summary()
        .get("system")
        .cloned()
        .unwrap_or_else(|| serde_json::json!({}));
    serde_json::to_string(&serde_json::json!({
        "secret": token,
        "events": events,
        "system": system,
    }))
    .map_err(|error| error.to_string())
}

pub fn push_pending_to_endpoint(endpoint: &str, token: &str) -> Result<usize, String> {
    let events = read_pending();
    let count = events.len();
    if count == 0 {
        return Ok(0);
    }

    let body = endpoint_body(&events, token)?;

    #[cfg(target_arch = "wasm32")]
    {
        let _ = endpoint;
        let _ = body;
        Err("push_telemetry is unavailable on wasm targets".to_string())
    }

    #[cfg(not(target_arch = "wasm32"))]
    {
        let status = reqwest::blocking::Client::builder()
            .timeout(std::time::Duration::from_secs(15))
            .build()
            .map_err(|error| error.to_string())?
            .post(endpoint)
            .header("Content-Type", "application/json")
            .header("User-Agent", format!("seraplot/{}", crate::VERSION))
            .body(body)
            .send()
            .map_err(|error| error.to_string())?
            .status()
            .as_u16();

        if status < 300 {
            clear_pending();
            Ok(count)
        } else {
            Err(format!("HTTP {status}"))
        }
    }
}

pub fn flush_pending() {
    let events = read_pending();
    if events.is_empty() {
        return;
    }

    let sent = events
        .iter()
        .filter(|event| try_send_event((*event).clone()))
        .count();

    if sent == events.len() {
        clear_pending();
    }
}

fn percentile(sorted: &[f64], fraction: f64) -> f64 {
    let idx = ((sorted.len() as f64 * fraction) as usize).min(sorted.len().saturating_sub(1));
    sorted.get(idx).copied().unwrap_or(0.0)
}

fn method_summary(durations: &[f64]) -> serde_json::Value {
    let count = durations.len();
    let total = durations.iter().sum::<f64>();
    let min = durations.iter().copied().fold(f64::MAX, f64::min);
    let max = durations.iter().copied().fold(0.0_f64, f64::max);
    let mut sorted = durations.to_vec();
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

    serde_json::json!({
        "count": count,
        "total_ms": round3(total),
        "min_ms": round3(min),
        "max_ms": round3(max),
        "avg_ms": round3(total / count as f64),
        "p50_ms": round3(percentile(&sorted, 0.5)),
        "p95_ms": round3(percentile(&sorted, 0.95)),
        "p99_ms": round3(percentile(&sorted, 0.99)),
    })
}

fn methods_summary(events: &[serde_json::Value]) -> HashMap<String, serde_json::Value> {
    let mut durations_by_method: HashMap<String, Vec<f64>> = HashMap::new();

    for event in events {
        let method_and_duration = event.get("method").and_then(|method| method.as_str()).zip(
            event
                .get("duration_ms")
                .and_then(|duration| duration.as_f64()),
        );

        if let Some((method, duration)) = method_and_duration {
            durations_by_method
                .entry(method.to_string())
                .or_default()
                .push(duration);
        }
    }

    durations_by_method
        .into_iter()
        .map(|(method, durations)| (method, method_summary(&durations)))
        .collect()
}

fn system_summary(events: &[serde_json::Value]) -> serde_json::Value {
    const SYSTEM_KEYS: [&str; 7] = [
        "os",
        "arch",
        "cpu_count",
        "ram_gb",
        "available_ram_gb",
        "cpu_brand",
        "python_version",
    ];

    events
        .first()
        .map(|event| {
            serde_json::Value::Object(serde_json::Map::from_iter(SYSTEM_KEYS.iter().map(|key| {
                (
                    (*key).to_string(),
                    event.get(*key).cloned().unwrap_or_default(),
                )
            })))
        })
        .unwrap_or_else(|| serde_json::json!({}))
}

pub fn get_metrics_summary() -> serde_json::Value {
    let events = read_pending();
    if events.is_empty() {
        return serde_json::json!({ "events": [] });
    }

    serde_json::json!({
        "system": system_summary(&events),
        "event_count": events.len(),
        "methods": methods_summary(&events),
        "events": events,
    })
}

pub fn push_telemetry(input: &str) -> String {
    #[derive(serde::Deserialize, Default)]
    struct Input {
        endpoint: Option<String>,
        token: Option<String>,
    }

    let payload: Input = serde_json::from_str(input).unwrap_or_default();
    let result = push_pending_to_endpoint(
        payload.endpoint.as_deref().unwrap_or(""),
        payload.token.as_deref().unwrap_or(""),
    );

    match result {
        Ok(count) => serde_json::json!({"ok": true, "count": count}).to_string(),
        Err(error) => serde_json::json!({"ok": false, "error": error}).to_string(),
    }
}
}

Configuration

Global and per-chart options: themes, palettes, tooltips, streaming, export, accessibility, and more.

Options globales et par graphique : thèmes, palettes, infobulles, streaming, export, accessibilité, et plus.

Background Configuration

Functions

set_global_background(color)

Sets a global background color applied to all subsequently created charts.

sp.set_global_background("#1a1a2e")
sp.set_global_background("#1a1a2e");
sp.set_global_background("#1a1a2e");
ParameterTypeDescription
colorstr / stringCSS color string (hex "#rrggbb", "rgb(…)", named color)

reset_global_background()

Clears the global background, reverting to the per-chart default.

sp.reset_global_background()
sp.reset_global_background();
sp.reset_global_background();

set_bg_fn(html, color)

Applies a background color to an existing HTML chart string. Returns the modified HTML string.

html_str = chart.to_html()
html_with_bg = sp.set_bg_fn(html_str, "#0f172a")
ParameterTypeDescription
htmlstrHTML string from Chart.to_html()
colorstrCSS background color

Returns: str — Modified HTML string. (Python only)


Examples

Dark theme dashboard

import seraplot as sp
sp.set_global_background("#0f172a")
bar = sp.build_bar_chart("Revenue", labels=["A", "B"], values=[300, 200])
pie = sp.build_pie_chart("Share",   labels=["A", "B"], values=[60, 40])
sp.reset_global_background()
const sp = require('seraplot');
sp.set_global_background("#0f172a");
const bar = sp.build_bar_chart("Revenue", ["A", "B"], { values: [300, 200] });
const pie = sp.build_pie_chart("Share",   ["A", "B"], { values: [60, 40] });
sp.reset_global_background();
import * as sp from 'seraplot';
sp.set_global_background("#0f172a");
const bar = sp.build_bar_chart("Revenue", ["A", "B"], { values: [300, 200] });
const pie = sp.build_pie_chart("Share",   ["A", "B"], { values: [60, 40] });
sp.reset_global_background();

Fonctions

set_global_background(color)

Définit une couleur de fond globale appliquée à tous les graphiques créés après l'appel.

ParamètreTypeDescription
colorstrCouleur CSS (hex "#rrggbb", "rgb(\u2026)", nom de couleur)

reset_global_background()

Efface le fond global, revenant à la valeur par défaut de chaque graphique.

set_bg_fn(html, color)

Applique une couleur de fond à une chaîne HTML existante. Retourne la chaîne HTML modifiée.

ParamètreTypeDescription
htmlstrChaîne HTML de Chart.to_html()
colorstrCouleur de fond CSS

Retourne : str — Chaîne HTML modifiée.


Exemples

import seraplot as sp

sp.set_global_background("#0f172a")

barre = sp.build_bar_chart("Revenus", labels=["A", "B"], values=[300, 200])
camembert = sp.build_pie_chart("Parts",   labels=["A", "B"], values=[60, 40])

sp.reset_global_background()

Palette & Couleurs

Overview

SeraPlot represents colors as 24-bit RGB integers (int) or CSS strings (str).

FormatExampleUsage
Hex integer0x6366f1color_hex, palette lists
CSS hex string"#6366f1"background, bg_color
CSS named color"navy"background, bg_color

Built-in Palettes

import seraplot as sp

sp.PALETTE_DEFAULT   # Indigo-based multi-color sequence
sp.PALETTE_COOL      # Blues and purples
sp.PALETTE_WARM      # Reds, oranges, yellows
sp.PALETTE_EARTH     # Browns and greens
sp.PALETTE_MONO      # Greyscale

Color Utility Reference

Parameter nameAcceptsDescription
color_hexintSingle element color
palettelist[int]Multi-element color list
backgroundstrChart canvas background
color_low / color_highintMin/max heatmap colors
color_up / color_downintRising/falling candle colors

Aperçu

SeraPlot représente les couleurs sous forme d'entiers RGB 24 bits (int) ou de chaînes CSS (str).

FormatExempleUtilisation
Entier hex0x6366f1color_hex, listes palette
Chaîne CSS hex"#6366f1"background, bg_color
Nom CSS"navy"background, bg_color

Palettes intégrées

import seraplot as sp

sp.PALETTE_DEFAULT   # Séquence multicolore à base d'indigo
sp.PALETTE_COOL      # Bleus et violets
sp.PALETTE_WARM      # Rouges, oranges, jaunes
sp.PALETTE_EARTH     # Bruns et verts
sp.PALETTE_MONO      # Niveaux de gris

Passez n'importe quelle liste d'entiers hex comme paramètre palette :

chart = sp.build_bar_chart(
    "Revenus",
    labels=["A","B","C"],
    values=[100,200,150],
    palette=[0x6366f1, 0x22d3ee, 0xf43f5e],
)

Référence des paramètres de couleur

Nom du paramètreAccepteDescription
color_hexintCouleur d'un élément unique
palettelist[int]Liste de couleurs multi-éléments
backgroundstrFond du canevas HTML
bg_colorstrFond du canevas 3D
color_lowintCouleur valeur min (heatmaps, choroplèthes)
color_midintCouleur valeur médiane
color_highintCouleur valeur max
color_upintCouleur bougie montante
color_downintCouleur bougie descendante
color_posintBarre positive (cascade)
color_negintBarre négative (cascade)
color_totalintBarre totale (cascade)

Exemples

import seraplot as sp

chart = sp.build_heatmap(
    "Corrélation",
    labels=["A","B","C"],
    flat_matrix=[1, 0.8, 0.2, 0.8, 1, 0.5, 0.2, 0.5, 1],
    color_low=0xfaf5ff,
    color_mid=0xa78bfa,
    color_high=0x4c1d95,
)

Themes

API

FunctionDescription
sp.theme(name)Apply a built-in theme — sets background, palette, and gridlines globally
sp.reset_theme()Revert to defaults (no background, default palette, no gridlines)
sp.themes()Returns a list of all available theme names
import seraplot as sp

sp.theme("dark")
chart = sp.bar("Revenue", labels, values)

sp.reset_theme()

All 7 themes

ThemeBackgroundGridlinesInspirationPrimary palette
"dark" #0f172aDeep space / Tailwind indigo
"light"transparentClean minimal
"scientific" #fafafaMatplotlib / D3 academic
"apple" #000000Apple dark mode (iOS/macOS)
"notion" #191919Notion editorial dark
"minimal"transparentMonochrome grayscale
"neon" #0a0a0aCyberpunk / retrowave

Full palette per theme

"dark"

[0x818CF8, 0xFB7185, 0x34D399, 0xFBBF24, 0xA78BFA,
 0x22D3EE, 0xF472B6, 0xA3E635, 0xF87171, 0x2DD4BF]

"light"

[0x6366F1, 0xF43F5E, 0x10B981, 0xF59E0B, 0x8B5CF6,
 0x06B6D4, 0xEC4899, 0x84CC16, 0xEF4444, 0x14B8A6]

"scientific"

[0x1F77B4, 0xFF7F0E, 0x2CA02C, 0xD62728, 0x9467BD,
 0x8C564B, 0xE377C2, 0x7F7F7F, 0xBCBD22, 0x17BECF]

"apple"

[0x0A84FF, 0x30D158, 0xFF453A, 0xFFD60A, 0xBF5AF2,
 0x64D2FF, 0xFF9F0A, 0xFF375F, 0xAC8E68, 0x63E6E2]

"notion"

[0xE3E3E3, 0xA0A0A0, 0xCB9D6D, 0x7C9E7E, 0x7B8FC4,
 0xC17B7B, 0xD4A76A, 0x8BA4B0, 0xB39DDB, 0x80CBC4]

"minimal"

[0x374151, 0x6B7280, 0x9CA3AF, 0xD1D5DB, 0x111827,
 0x4B5563, 0x1F2937, 0xE5E7EB, 0x030712, 0x6B7280]

"neon"

[0x00FFF0, 0xFF00FF, 0x00FF41, 0xFF6B00, 0xFFFF00,
 0xFF1493, 0x00BFFF, 0xFF4500, 0x7FFF00, 0xDA70D6]

Examples

import seraplot as sp

sp.theme("dark")
sp.bar("Revenue", ["Q1", "Q2", "Q3", "Q4"], [120, 145, 98, 180]).show()

sp.theme("neon")
sp.scatter("Clusters", x, y).show()

sp.theme("scientific")
sp.line("Population Growth", years, values).show()

sp.reset_theme()
print(sp.themes())
# ['dark', 'light', 'scientific', 'apple', 'notion', 'minimal', 'neon']

Notes

  • sp.theme() sets the global background, palette, and gridlines. It is equivalent to calling sp.config(background=..., palette=..., gridlines=...) with the preset values.
  • Themes persist until sp.reset_theme() or sp.config() overrides them.
  • You can further override individual properties after calling a theme:
sp.theme("dark")
sp.config(font_size=16, border_radius=12)

API

FonctionDescription
sp.theme(name)Applique un thème intégré — définit le fond, la palette et le quadrillage globalement
sp.reset_theme()Revient aux valeurs par défaut (pas de fond, palette par défaut, pas de quadrillage)
sp.themes()Retourne la liste de tous les noms de thèmes disponibles
import seraplot as sp

sp.theme("dark")
graphique = sp.bar("Revenus", labels, values)

sp.reset_theme()

Les 7 thèmes disponibles

ThèmeFondQuadrillageInspirationPalette principale
"dark" #0f172aEspace profond / indigo Tailwind
"light"transparentÉpuré minimal
"scientific" #fafafaMatplotlib / D3 académique
"apple" #000000Mode sombre Apple (iOS/macOS)
"notion" #191919Notion éditorial sombre
"minimal"transparentNuances de gris monochrome
"neon" #0a0a0aCyberpunk / retrowave

Palettes complètes

"dark"

[0x818CF8, 0xFB7185, 0x34D399, 0xFBBF24, 0xA78BFA,
 0x22D3EE, 0xF472B6, 0xA3E635, 0xF87171, 0x2DD4BF]

"light"

[0x6366F1, 0xF43F5E, 0x10B981, 0xF59E0B, 0x8B5CF6,
 0x06B6D4, 0xEC4899, 0x84CC16, 0xEF4444, 0x14B8A6]

"scientific"

[0x1F77B4, 0xFF7F0E, 0x2CA02C, 0xD62728, 0x9467BD,
 0x8C564B, 0xE377C2, 0x7F7F7F, 0xBCBD22, 0x17BECF]

"apple"

[0x0A84FF, 0x30D158, 0xFF453A, 0xFFD60A, 0xBF5AF2,
 0x64D2FF, 0xFF9F0A, 0xFF375F, 0xAC8E68, 0x63E6E2]

"notion"

[0xE3E3E3, 0xA0A0A0, 0xCB9D6D, 0x7C9E7E, 0x7B8FC4,
 0xC17B7B, 0xD4A76A, 0x8BA4B0, 0xB39DDB, 0x80CBC4]

"minimal"

[0x374151, 0x6B7280, 0x9CA3AF, 0xD1D5DB, 0x111827,
 0x4B5563, 0x1F2937, 0xE5E7EB, 0x030712, 0x6B7280]

"neon"

[0x00FFF0, 0xFF00FF, 0x00FF41, 0xFF6B00, 0xFFFF00,
 0xFF1493, 0x00BFFF, 0xFF4500, 0x7FFF00, 0xDA70D6]

Exemples

import seraplot as sp

sp.theme("dark")
sp.bar("Revenus", ["T1", "T2", "T3", "T4"], [120, 145, 98, 180]).show()

sp.theme("neon")
sp.scatter("Clusters", x, y).show()

sp.theme("scientific")
sp.line("Croissance démographique", annees, valeurs).show()

sp.reset_theme()
print(sp.themes())
# ['dark', 'light', 'scientific', 'apple', 'notion', 'minimal', 'neon']

Notes

  • sp.theme() définit le fond global, la palette et le quadrillage. C'est équivalent à sp.config(background=..., palette=..., gridlines=...) avec les valeurs du préréglage.
  • Les thèmes persistent jusqu'à sp.reset_theme() ou un appel sp.config() qui les écrase.
  • Vous pouvez continuer à surcharger des propriétés individuelles après avoir appliqué un thème :
sp.theme("dark")
sp.config(font_size=16, border_radius=12)

Infobulles personnalisées

Signature

sp.build_hover_json(
    *,
    fields: list[str],
    values: list[list[str | float]],
    format: str = "table",
) -> str

Description

Builds a JSON string suitable for the hover_json parameter accepted by most chart functions.


Parameters

ParameterTypeDefaultDescription
fieldslist[str]requiredColumn headers for the tooltip
valueslist[list[str | float]]requiredOne inner list per data point
formatstr"table"Tooltip layout: "table" or "list"

Signature

sp.build_hover_json(
    *,
    fields: list[str],
    values: list[list[str | float]],
    format: str = "table",
) -> str

Description

Construit une chaîne JSON adaptée au paramètre hover_json accepté par la plupart des fonctions graphiques.


Paramètres

ParamètreTypeDéfautDescription
fieldslist[str]requisEn-têtes de colonnes de l'infobulle
valueslist[list[str | float]]requisUne liste par point de données
formatstr"table"Mise en page : "table" ou "list"

Retourne

str — Chaîne JSON à passer au paramètre hover_json=.


Exemples

import seraplot as sp

hover = sp.build_hover_json(
    fields=["Produit", "Revenu (€)", "Croissance"],
    values=[
        ["Alpha", 420, "+12%"],
        ["Bêta",  380, "+5%"],
        ["Gamma", 290, "-3%"],
    ],
)

chart = sp.build_bar_chart(
    "Revenus par produit",
    labels=["Alpha", "Bêta", "Gamma"],
    values=[420, 380, 290],
    hover_json=hover,
)

Affichage automatique (Jupyter)

Signature

sp.set_auto_display(enabled: bool) -> None

Description

Controls whether Chart objects are automatically rendered inline in Jupyter notebooks when they are the last expression of a cell.

StateBehavior
True (default)chart at end of cell → rendered immediately
FalseMust call display(chart) or chart.show() explicitly

Parameters

ParameterTypeDescription
enabledboolTrue to enable auto-display, False to disable

Examples

sp.set_auto_display(False)
charts = []
for name, values in datasets.items():
    charts.append(sp.build_bar_chart(name, labels=["A","B","C"], values=values))
for c in charts:
    c.show()

Signature

sp.set_auto_display(enabled: bool) -> None

Description

Contrôle si les objets Chart sont automatiquement rendus dans les cellules Jupyter.

ÉtatComportement
True (défaut)Le graphique en fin de cellule est rendu immédiatement
FalseIl faut appeler display(chart) ou chart.show() explicitement

Paramètres

ParamètreTypeDescription
enabledboolTrue pour activer, False pour désactiver

Exemples

sp.set_auto_display(False)
graphiques = []
for nom, valeurs in jeux_de_donnees.items():
    graphiques.append(sp.build_bar_chart(nom, labels=["A","B","C"], values=valeurs))
for g in graphiques:
    g.show()

Faceting / Small Multiples

Combine multiple charts into a grid layout — one call instead of manually composing HTML.

Python

import seraplot as sp

charts = [sp.bar([1,2,3], ["a","b","c"], title=region) for region in ["EU","US","APAC"]]
grid = sp.facet(charts, cols=3, gap=12, cell_height=400)
grid.save("regions.html")

JavaScript

import { buildGrid } from "seraplot";
const html = buildGrid(JSON.stringify({ charts: [chart1Html, chart2Html], cols: 2 }));

Parameters

NameTypeDefaultDescription
chartslist[Chart]requiredCharts to lay out
colsint2Columns per row
gapint16Gap in pixels
bgstrNoneBackground color
cell_heightint520Per-cell height

Combine plusieurs charts dans une grille — un seul appel au lieu de composer le HTML manuellement.

Python

import seraplot as sp

charts = [sp.bar([1,2,3], ["a","b","c"], title=region) for region in ["EU","US","APAC"]]
grid = sp.facet(charts, cols=3, gap=12, cell_height=400)
grid.save("regions.html")

JavaScript

import { buildGrid } from "seraplot";
const html = buildGrid(JSON.stringify({ charts: [chart1Html, chart2Html], cols: 2 }));

Paramètres

NomTypeDéfautDescription
chartslist[Chart]requisCharts à disposer
colsint2Colonnes par ligne
gapint16Espacement en pixels
bgstrNoneCouleur de fond
cell_heightint520Hauteur par cellule

Downsampling (LTTB)

Reduce massive datasets while preserving visual shape using the Largest-Triangle-Three-Buckets algorithm. A 10M-point scatter chart becomes 5K points indistinguishable to the eye.

Python

import seraplot as sp

chart = sp.scatter(big_x, big_y).downsample(n=5000)

points = sp.lttb(list(zip(big_x, big_y)), threshold=5000)

JavaScript

import { downsampleLttb } from "seraplot";
const reduced = JSON.parse(downsampleLttb(JSON.stringify({ x, y, threshold: 5000 })));

Why LTTB?

MethodPreserves peaksSpeedVisual fidelity
Random sampleNoFastPoor
Every-NthMaybeFastOK
LTTBYesFastExcellent

Réduit les datasets massifs en préservant la forme visuelle avec l'algorithme Largest-Triangle-Three-Buckets. Un scatter de 10M points devient 5K points indistinguables à l'œil.

Python

import seraplot as sp

chart = sp.scatter(big_x, big_y).downsample(n=5000)

points = sp.lttb(list(zip(big_x, big_y)), threshold=5000)

JavaScript

import { downsampleLttb } from "seraplot";
const reduced = JSON.parse(downsampleLttb(JSON.stringify({ x, y, threshold: 5000 })));

Pourquoi LTTB ?

MéthodePréserve les picsVitesseFidélité visuelle
Échantillon aléatoireNonRapideMauvaise
Tous les NPeut-êtreRapideOK
LTTBOuiRapideExcellente

Live Streaming

LiveStream is a tiny, allocation-aware accumulator that turns a series of (x, y) samples arriving over time into a fully-rendered SeraPlot Chart. It maintains a bounded ring buffer (the max_points window) so memory is constant whatever the duration of the stream.

The same engine is exposed in JavaScript as chartAppend(...), but Python gets the dedicated stateful class because it's by far the most common language for live data pipelines (sensors, sockets, message buses, ML training loops, etc.).


Constructor

sp.LiveStream(
    kind: str = "line",        # "line" or "scatter"
    title: str = "",
    max_points: int = 500,     # ring buffer size
    color_hex: int = 0x6366F1,
    width: int = 900,
    height: int = 420,
)
ParameterTypeDefaultDescription
kindstr"line"Chart kind. "line" (categorical X) or "scatter" (numeric X).
titlestr""Chart title rendered on every render().
max_pointsint500Maximum samples kept in the buffer. Older samples are dropped from the head.
color_hexint0x6366F1Series colour as a 24-bit RGB integer.
widthint900Canvas width in pixels.
heightint420Canvas height in pixels.

Methods

MethodEffect
push(x, y)Append a single sample.
extend(xs, ys)Append two lists in lock-step.
render() -> ChartRe-render the current buffer and return a fresh Chart.
clear()Empty the buffer.
n (getter)Current sample count.

Every mutating call enforces the max_points cap by dropping the oldest samples — so the buffer is always bounded.


Example: Jupyter live plot

import seraplot as sp
import time, random
from IPython.display import display, clear_output

stream = sp.LiveStream(kind="line", title="Sensor", max_points=200)

for t in range(2000):
    stream.push(t, 50 + 10 * random.gauss(0, 1))
    if t % 20 == 0:
        clear_output(wait=True)
        display(stream.render())
        time.sleep(0.05)

Example: WebSocket / Kafka feed

async def consume(ws):
    stream = sp.LiveStream(kind="scatter", max_points=10_000)
    async for msg in ws:
        x, y = parse(msg)
        stream.push(x, y)
        if stream.n % 250 == 0:
            broadcast_chart(stream.render())

Underlying primitive (universal)

Internally LiveStream.render() calls the universal chart_append function. The same primitive is reachable from JavaScript and the C-FFI:

import * as sp from "seraplot";

let prev_x = [], prev_y = [];

function tick(x, y) {
  const out = JSON.parse(sp.chartAppend(JSON.stringify({
    kind: "line",
    title: "Sensor",
    x: [x], y: [y],
    prev_x, prev_y,
    max_points: 500,
  })));
  prev_x = out.x;
  prev_y = out.y;
  document.getElementById("plot").innerHTML = out.html;
}

The JSON payload {kind, x, y, prev_x, prev_y, max_points, title, color_hex, width, height} is the contract — the same shape applies in any host language.

LiveStream est un petit accumulateur économe en allocation qui transforme une série d'échantillons (x, y) arrivant dans le temps en un Chart SeraPlot entièrement rendu. Il maintient un buffer circulaire borné (la fenêtre max_points), donc la mémoire reste constante quelle que soit la durée du flux.

Le même moteur est exposé en JavaScript via chartAppend(...), mais Python obtient une classe à état dédiée parce que c'est de loin le langage le plus utilisé pour les pipelines de données live (capteurs, sockets, bus de messages, boucles d'entraînement ML, etc.).


Constructeur

sp.LiveStream(
    kind: str = "line",        # "line" ou "scatter"
    title: str = "",
    max_points: int = 500,     # taille du buffer circulaire
    color_hex: int = 0x6366F1,
    width: int = 900,
    height: int = 420,
)
ParamètreTypeDéfautDescription
kindstr"line"Type de graphique. "line" (X catégoriel) ou "scatter" (X numérique).
titlestr""Titre rendu à chaque render().
max_pointsint500Nombre maximum d'échantillons gardés. Les plus anciens sont supprimés en tête.
color_hexint0x6366F1Couleur de la série en entier RGB 24 bits.
widthint900Largeur du canvas en pixels.
heightint420Hauteur du canvas en pixels.

Méthodes

MéthodeEffet
push(x, y)Ajoute un échantillon unique.
extend(xs, ys)Ajoute deux listes en parallèle.
render() -> ChartRe-rend le buffer courant et retourne un nouveau Chart.
clear()Vide le buffer.
n (getter)Nombre d'échantillons courant.

Chaque appel mutant applique la limite max_points en supprimant les échantillons les plus anciens — le buffer est donc toujours borné.


Exemple : plot live dans Jupyter

import seraplot as sp
import time, random
from IPython.display import display, clear_output

stream = sp.LiveStream(kind="line", title="Capteur", max_points=200)

for t in range(2000):
    stream.push(t, 50 + 10 * random.gauss(0, 1))
    if t % 20 == 0:
        clear_output(wait=True)
        display(stream.render())
        time.sleep(0.05)

Exemple : flux WebSocket / Kafka

async def consume(ws):
    stream = sp.LiveStream(kind="scatter", max_points=10_000)
    async for msg in ws:
        x, y = parse(msg)
        stream.push(x, y)
        if stream.n % 250 == 0:
            broadcast_chart(stream.render())

Primitive sous-jacente (universelle)

En interne, LiveStream.render() appelle la fonction universelle chart_append. La même primitive est accessible depuis JavaScript et le C-FFI :

import * as sp from "seraplot";

let prev_x = [], prev_y = [];

function tick(x, y) {
  const out = JSON.parse(sp.chartAppend(JSON.stringify({
    kind: "line",
    title: "Capteur",
    x: [x], y: [y],
    prev_x, prev_y,
    max_points: 500,
  })));
  prev_x = out.x;
  prev_y = out.y;
  document.getElementById("plot").innerHTML = out.html;
}

Le payload JSON {kind, x, y, prev_x, prev_y, max_points, title, color_hex, width, height} est le contrat — la même forme s'applique dans n'importe quelle langue hôte.

Chart Diff

Compare two charts structurally — useful for visual CI / regression testing.

Python

import seraplot as sp

a = sp.bar([1,2,3], ["x","y","z"])
b = sp.bar([1,2,4], ["x","y","z"])
result = a.diff(b)
print(result)

Returns JSON: { "ok": true, "identical": false, "size_a": 4521, "size_b": 4523, "common_prefix": 4400, "similarity": 0.97 }.

JavaScript

import { chartDiff } from "seraplot";
const diff = JSON.parse(chartDiff(JSON.stringify({ a: htmlA, b: htmlB })));

Compare deux charts structurellement — utile pour les CI visuelles / tests de régression.

Python

import seraplot as sp

a = sp.bar([1,2,3], ["x","y","z"])
b = sp.bar([1,2,4], ["x","y","z"])
result = a.diff(b)
print(result)

Retourne du JSON : { "ok": true, "identical": false, "size_a": 4521, "size_b": 4523, "common_prefix": 4400, "similarity": 0.97 }.

JavaScript

import { chartDiff } from "seraplot";
const diff = JSON.parse(chartDiff(JSON.stringify({ a: htmlA, b: htmlB })));

Drift Detection

Detect distribution shift between a reference dataset and a current one using the Kolmogorov-Smirnov two-sample test.

Python

import seraplot as sp
import json

result = json.loads(sp.drift(reference=ref_values, current=cur_values))
print(result)

Returns:

{
  "ok": true,
  "ks_statistic": 0.18,
  "p_value": 0.003,
  "drift_detected": true,
  "n_reference": 1000,
  "n_current": 1000
}

drift_detected is true when p_value < 0.05.

JavaScript

import { driftKs } from "seraplot";
const r = JSON.parse(driftKs(JSON.stringify({ reference, current })));

Détecte un drift de distribution entre un dataset de référence et un dataset actuel via le test à deux échantillons de Kolmogorov-Smirnov.

Python

import seraplot as sp
import json

result = json.loads(sp.drift(reference=ref_values, current=cur_values))
print(result)

Retourne :

{
  "ok": true,
  "ks_statistic": 0.18,
  "p_value": 0.003,
  "drift_detected": true,
  "n_reference": 1000,
  "n_current": 1000
}

drift_detected est true quand p_value < 0.05.

JavaScript

import { driftKs } from "seraplot";
const r = JSON.parse(driftKs(JSON.stringify({ reference, current })));

AutoML & Pipeline

auto_classify

Try several classifiers, return the leaderboard sorted by score.

import seraplot as sp

result = sp.auto_classify(X_train, y_train)
print(result["best_model"], result["best_score"])
for row in result["leaderboard"]:
    print(row)

Default models (2.3.89+): knn, decision_tree, gradient_boosting. The previous defaults logistic and random_forest are still available via models=["logistic","random_forest"] but were dropped from defaults pending stability fixes. Customize freely with e.g. models=["knn","gradient_boosting"].

Failed/panicking models are caught: their leaderboard entry has score = NaN and is sorted last.

Pipeline

Chain transformers + estimator (sklearn-compatible API).

from seraplot import StandardScaler, RandomForestClassifier, Pipeline

pipe = Pipeline([
    ("scaler", StandardScaler()),
    ("model",  RandomForestClassifier(n_estimators=200)),
])
pipe.fit(X_train, y_train)
preds = pipe.predict(X_test)

auto_classify

Essaie plusieurs classifieurs, retourne le leaderboard trié par score.

import seraplot as sp

result = sp.auto_classify(X_train, y_train)
print(result["best_model"], result["best_score"])
for row in result["leaderboard"]:
    print(row)

Modèles par défaut (2.3.89+) : knn, decision_tree, gradient_boosting. Les anciens défauts logistic et random_forest restent disponibles via models=["logistic","random_forest"] mais ont été retirés en attendant un correctif de stabilité. Personnalisable librement, ex. models=["knn","gradient_boosting"].

Les modèles qui échouent/paniquent sont capturés : leur entrée du leaderboard a score = NaN et passe en dernier.

Pipeline

Enchaîne transformers + estimateur (API compatible sklearn).

from seraplot import StandardScaler, RandomForestClassifier, Pipeline

pipe = Pipeline([
    ("scaler", StandardScaler()),
    ("model",  RandomForestClassifier(n_estimators=200)),
])
pipe.fit(X_train, y_train)
preds = pipe.predict(X_test)

Export (SVG / PNG / Data URL / HTML)

SeraPlot exposes a small, language-universal export layer. Every function below is registered through the same for_each_fn! macro, so the exact same behaviour is available from Python, JavaScript and the C-FFI.

The Python wrappers accept a Chart object directly (ergonomic sugar). The JavaScript / FFI wrappers take a JSON string — the chart's .html field must be passed inside {"html": "..."}.


sp.savefig(chart, path)

Write the complete HTML of the chart to disk. The file is fully self-contained: it embeds the SVG, its scripts and styles. It can be opened in any browser, attached to an email, or served statically — no server, no CDN.

import seraplot as sp

chart = sp.build_bar_chart("Revenue", ["Q1", "Q2"], [120, 180])
sp.savefig(chart, "revenue.html")

Errors are surfaced as IOError.


sp.export_svg(chart) -> str

Returns the raw <svg>...</svg> block extracted from the chart. Useful for:

  • Embedding the chart into a LaTeX / Word / Illustrator workflow
  • Post-processing the geometry (CSS overrides, masks, custom filters)
  • Server-side rasterisation with cairosvg, resvg, librsvg, etc.
svg = sp.export_svg(chart)
with open("plot.svg", "w", encoding="utf-8") as f:
    f.write(svg)

Returns an empty string if no <svg> tag is found in the chart HTML.


sp.export_png(chart, path)

Writes the SVG of the chart to disk under path. If path does not end in .svg, the extension is rewritten to .svg. To convert to a true PNG raster, pipe through any external converter — this keeps the binary small and avoids shipping a 30 MB rasteriser as a hard dependency.

sp.export_png(chart, "plot.svg")

import cairosvg
cairosvg.svg2png(url="plot.svg", write_to="plot.png", output_width=1920)

A ValueError is raised if the chart contains no <svg> block.


sp.export_data_url(chart) -> str

Returns a data:image/svg+xml;base64,... URL that can be dropped directly into an <img src="...">, a CSS background-image: url(...), or any HTML email.

url = sp.export_data_url(chart)
html = f'<img src="{url}" alt="Plot" />'

sp.chart_info(chart) -> str

Returns a JSON string with structural metadata about the rendered chart. Handy for logging, telemetry, or asserting chart complexity in unit tests.

import json
info = json.loads(sp.chart_info(chart))
print(info)
{"size": 18432, "paths": 12, "rects": 47, "circles": 0, "has_svg": true}

JavaScript

import * as sp from "seraplot";

const chart = sp.buildBarChart(JSON.stringify({
  title: "Revenue",
  labels: ["Q1", "Q2"],
  values: [120, 180],
}));

const svg     = sp.exportSvg(JSON.stringify({ html: chart }));
const dataUrl = sp.exportDataUrl(JSON.stringify({ html: chart }));
const written = sp.exportHtmlFile(JSON.stringify({ html: chart, path: "out.html" }));
const meta    = JSON.parse(sp.chartInfo(JSON.stringify({ html: chart })));

SeraPlot expose une petite couche d'export universelle entre langages. Chaque fonction ci-dessous est enregistrée via la même macro for_each_fn!, le comportement est donc strictement identique depuis Python, JavaScript et le C-FFI.

Les wrappers Python acceptent directement un objet Chart (sucre ergonomique). Côté JavaScript / FFI, on passe une chaîne JSON — le champ .html du chart doit être placé dans {"html": "..."}.


sp.savefig(chart, path)

Écrit l'intégralité du HTML du chart sur disque. Le fichier est auto-suffisant : il embarque le SVG, ses scripts et ses styles. Il s'ouvre dans n'importe quel navigateur, peut être joint à un mail ou servi en statique — aucun serveur, aucun CDN.

import seraplot as sp

chart = sp.build_bar_chart("Chiffre d'affaires", ["T1", "T2"], [120, 180])
sp.savefig(chart, "revenue.html")

Les erreurs remontent en IOError.


sp.export_svg(chart) -> str

Retourne le bloc <svg>...</svg> brut extrait du chart. Utile pour :

  • Embarquer le chart dans un flux LaTeX / Word / Illustrator
  • Post-traiter la géométrie (overrides CSS, masques, filtres custom)
  • Rasteriser côté serveur avec cairosvg, resvg, librsvg, etc.
svg = sp.export_svg(chart)
with open("plot.svg", "w", encoding="utf-8") as f:
    f.write(svg)

Retourne une chaîne vide si aucune balise <svg> n'est trouvée.


sp.export_png(chart, path)

Écrit le SVG du chart sur disque sous path. Si path ne finit pas par .svg, l'extension est réécrite en .svg. Pour obtenir un vrai PNG raster, on passe par un convertisseur externe — cela garde le binaire compact et évite d'embarquer un rasteriseur de 30 Mo en dépendance dure.

sp.export_png(chart, "plot.svg")

import cairosvg
cairosvg.svg2png(url="plot.svg", write_to="plot.png", output_width=1920)

Un ValueError est levé si le chart ne contient aucun bloc <svg>.


sp.export_data_url(chart) -> str

Retourne une URL data:image/svg+xml;base64,... directement injectable dans un <img src="...">, un background-image: url(...) CSS, ou n'importe quel mail HTML.

url = sp.export_data_url(chart)
html = f'<img src="{url}" alt="Graphique" />'

sp.chart_info(chart) -> str

Retourne une chaîne JSON contenant des métadonnées structurelles sur le chart rendu. Pratique pour le logging, la télémétrie ou pour tester la complexité d'un chart dans des tests unitaires.

import json
info = json.loads(sp.chart_info(chart))
print(info)
{"size": 18432, "paths": 12, "rects": 47, "circles": 0, "has_svg": true}

JavaScript

import * as sp from "seraplot";

const chart = sp.buildBarChart(JSON.stringify({
  title: "Chiffre d'affaires",
  labels: ["T1", "T2"],
  values: [120, 180],
}));

const svg     = sp.exportSvg(JSON.stringify({ html: chart }));
const dataUrl = sp.exportDataUrl(JSON.stringify({ html: chart }));
const written = sp.exportHtmlFile(JSON.stringify({ html: chart, path: "out.html" }));
const meta    = JSON.parse(sp.chartInfo(JSON.stringify({ html: chart })));

ML Model Persistence

SeraPlot ships two universal primitives for serialising ML model state to a language-agnostic JSON envelope. They are exposed through for_each_fn!, so the exact same wire format is reachable from Python, JavaScript and the C-FFI. A model trained in a Python notebook can be reloaded in a Node service or a browser, and vice-versa.

The envelope shape is intentionally simple:

{
  "seraplot_model_v": 1,
  "kind": "kmeans",
  "state": { "...": "model-specific JSON" }
}

This makes the persistence layer trivial to inspect, diff, version-control, encrypt or sign. No pickle, no custom binary, no security risk.


sp.ml_save_model(payload: str) -> str

Saves a JSON envelope. The input is a JSON string with three fields:

FieldTypeDescription
kindstrFree-form model identifier (e.g. "kmeans", "random_forest").
stateanyModel-specific JSON state (centroids, coefficients, tree splits...).
pathstr?Optional file path. If absent, the envelope is returned inline in the response.
import seraplot as sp
import json

centroids = [[0.1, 0.2], [4.5, 3.7]]
out = sp.ml_save_model(json.dumps({
    "kind": "kmeans",
    "state": {"k": 2, "centroids": centroids, "inertia": 12.3},
    "path": "kmeans.json",
}))

print(out)
{"ok": true, "path": "kmeans.json", "size": 87}

If path is omitted, the envelope is returned in the data field:

out = sp.ml_save_model(json.dumps({"kind": "kmeans", "state": {...}}))
parsed = json.loads(out)
serialised_blob = parsed["data"]   # ready to upload, encrypt, embed...

sp.ml_load_model(payload: str) -> str

Loads a previously saved envelope from disk or from an inline JSON string.

out = sp.ml_load_model(json.dumps({"path": "kmeans.json"}))
parsed = json.loads(out)
model = parsed["model"]   # {"seraplot_model_v":1,"kind":"kmeans","state":{...}}
out = sp.ml_load_model(json.dumps({"data": serialised_blob}))

The response is always:

{"ok": true, "model": { "seraplot_model_v": 1, "kind": "...", "state": {...} }}

or, on failure:

{"ok": false, "error": "..."}

End-to-end: train → save → reload → predict

import seraplot as sp
import json, numpy as np

X = np.random.randn(1000, 2)
km = sp.KMeans(k=4)
km.fit(X)

state = {
    "k": km.k,
    "centroids": km.centroids_,
    "inertia": km.inertia_,
    "n_iter": km.n_iter_,
}
sp.ml_save_model(json.dumps({"kind": "kmeans", "state": state, "path": "km.json"}))

loaded = json.loads(sp.ml_load_model(json.dumps({"path": "km.json"})))["model"]
assert loaded["state"]["centroids"] == state["centroids"]

JavaScript

import * as sp from "seraplot";

const out = sp.mlSaveModel(JSON.stringify({
  kind: "kmeans",
  state: { centroids: [[0,0],[1,1]] },
  path: "km.json",
}));

const loaded = JSON.parse(sp.mlLoadModel(JSON.stringify({ path: "km.json" })));
console.log(loaded.model.state.centroids);

Why JSON instead of pickle / bincode?

  • Cross-language — the envelope works in Python, JS, C, Rust without any binary protocol negotiation.
  • Audit-friendly — the file is human-readable, fits Git diffs and is trivial to redact PII from.
  • Safe — no arbitrary code execution on load, unlike pickle or joblib.
  • Compressible — gzipped JSON state is typically within 5–15 % of a binary serialisation for tabular ML models, with negligible parse cost.

SeraPlot fournit deux primitives universelles pour sérialiser l'état d'un modèle ML dans une enveloppe JSON indépendante du langage. Elles sont exposées via for_each_fn!, donc le format de fil exact est accessible depuis Python, JavaScript et le C-FFI. Un modèle entraîné dans un notebook Python peut être rechargé dans un service Node ou dans le navigateur, et inversement.

La forme de l'enveloppe est volontairement minimale :

{
  "seraplot_model_v": 1,
  "kind": "kmeans",
  "state": { "...": "JSON spécifique au modèle" }
}

La couche de persistance est ainsi triviale à inspecter, à diff-er, à versionner, à chiffrer ou à signer. Pas de pickle, pas de binaire custom, pas de risque de sécurité.


sp.ml_save_model(payload: str) -> str

Sauvegarde une enveloppe JSON. L'entrée est une chaîne JSON avec trois champs :

ChampTypeDescription
kindstrIdentifiant libre du modèle (ex. "kmeans", "random_forest").
stateanyÉtat JSON spécifique au modèle (centroïdes, coefficients, splits d'arbre...).
pathstr?Chemin de fichier optionnel. Si absent, l'enveloppe est renvoyée en ligne dans la réponse.
import seraplot as sp
import json

centroids = [[0.1, 0.2], [4.5, 3.7]]
out = sp.ml_save_model(json.dumps({
    "kind": "kmeans",
    "state": {"k": 2, "centroids": centroids, "inertia": 12.3},
    "path": "kmeans.json",
}))

print(out)
{"ok": true, "path": "kmeans.json", "size": 87}

Si path est omis, l'enveloppe est renvoyée dans le champ data :

out = sp.ml_save_model(json.dumps({"kind": "kmeans", "state": {...}}))
parsed = json.loads(out)
serialised_blob = parsed["data"]

sp.ml_load_model(payload: str) -> str

Recharge une enveloppe précédemment sauvée depuis disque ou depuis une chaîne JSON en mémoire.

out = sp.ml_load_model(json.dumps({"path": "kmeans.json"}))
parsed = json.loads(out)
model = parsed["model"]
out = sp.ml_load_model(json.dumps({"data": serialised_blob}))

La réponse est toujours :

{"ok": true, "model": { "seraplot_model_v": 1, "kind": "...", "state": {...} }}

ou, en cas d'échec :

{"ok": false, "error": "..."}

Bout-en-bout : entraînement → sauvegarde → recharge → prédiction

import seraplot as sp
import json, numpy as np

X = np.random.randn(1000, 2)
km = sp.KMeans(k=4)
km.fit(X)

state = {
    "k": km.k,
    "centroids": km.centroids_,
    "inertia": km.inertia_,
    "n_iter": km.n_iter_,
}
sp.ml_save_model(json.dumps({"kind": "kmeans", "state": state, "path": "km.json"}))

loaded = json.loads(sp.ml_load_model(json.dumps({"path": "km.json"})))["model"]
assert loaded["state"]["centroids"] == state["centroids"]

JavaScript

import * as sp from "seraplot";

const out = sp.mlSaveModel(JSON.stringify({
  kind: "kmeans",
  state: { centroids: [[0,0],[1,1]] },
  path: "km.json",
}));

const loaded = JSON.parse(sp.mlLoadModel(JSON.stringify({ path: "km.json" })));
console.log(loaded.model.state.centroids);

Pourquoi JSON plutôt que pickle / bincode ?

  • Cross-language — l'enveloppe fonctionne en Python, JS, C, Rust sans négociation de protocole binaire.
  • Auditable — le fichier est lisible, s'intègre aux diffs Git et permet de retirer trivialement les PII.
  • Sûr — aucune exécution de code arbitraire au chargement, contrairement à pickle ou joblib.
  • Compressible — un état JSON gzippé pèse typiquement entre 5 et 15 % de plus qu'une sérialisation binaire pour des modèles ML tabulaires, avec un coût de parsing négligeable.

Pickle / Serialization

Chart objects are picklable via __getstate__ / __setstate__ — works with joblib, multiprocessing, Ray, Streamlit reruns.

Python

import seraplot as sp
import pickle

chart = sp.bar([1,2,3], ["a","b","c"])
blob = pickle.dumps(chart)

restored = pickle.loads(blob)
restored.save("restored.html")

Internally, only the HTML string is serialized — minimal payload, no transient state.

ML models

Native ml_save_model / ml_load_model are registered in the Rust core but not yet exposed as Python attributes in 2.3.89. For now use stdlib pickle directly on fitted estimators:

import pickle
from seraplot import KNeighborsClassifier

clf = KNeighborsClassifier(k=5).fit(X, y)
blob = pickle.dumps(clf)
restored = pickle.loads(blob)

Les objets Chart sont sérialisables via __getstate__ / __setstate__ — compatible joblib, multiprocessing, Ray, reruns Streamlit.

Python

import seraplot as sp
import pickle

chart = sp.bar([1,2,3], ["a","b","c"])
blob = pickle.dumps(chart)

restored = pickle.loads(blob)
restored.save("restored.html")

En interne, seule la chaîne HTML est sérialisée — payload minimal, aucun état transitoire.

Modèles ML

Les fonctions natives ml_save_model / ml_load_model sont enregistrées dans le cœur Rust mais pas encore exposées comme attributs Python en 2.3.89. Utilisez pickle standard sur les estimateurs entraînés :

import pickle
from seraplot import KNeighborsClassifier

clf = KNeighborsClassifier(k=5).fit(X, y)
blob = pickle.dumps(clf)
restored = pickle.loads(blob)

Accessibility (a11y)

Inject ARIA roles, <title> and <desc> into the chart SVG for screen readers and B2B compliance (WCAG 2.1).

Python

import seraplot as sp

chart = (
    sp.bar([10,20,30], ["EU","US","APAC"])
      .a11y(title="Quarterly revenue by region",
            desc="Bar chart, EU 10M, US 20M, APAC 30M")
)

The resulting SVG includes role="img", aria-label, <title>, <desc> — recognized by NVDA, JAWS, VoiceOver.

Injecte les rôles ARIA, <title> et <desc> dans le SVG pour les lecteurs d'écran et la conformité B2B (WCAG 2.1).

Python

import seraplot as sp

chart = (
    sp.bar([10,20,30], ["EU","US","APAC"])
      .a11y(title="Revenu trimestriel par région",
            desc="Bar chart, EU 10M, US 20M, APAC 30M")
)

Le SVG résultant inclut role="img", aria-label, <title>, <desc> — reconnus par NVDA, JAWS, VoiceOver.

CSP-safe Mode

Strict Content Security Policies block inline <script>. The csp_safe() method extracts JS into a <script type="application/json"> payload + a single nonce-able loader.

Python

import seraplot as sp

chart = sp.line([1,2,3,4], [10,20,15,25]).csp_safe()

Apply your CSP script-src 'nonce-sp-nonce' and the chart still renders.

Les CSP strictes bloquent les <script> inline. La méthode csp_safe() extrait le JS dans un payload <script type="application/json"> + un loader unique compatible nonce.

Python

import seraplot as sp

chart = sp.line([1,2,3,4], [10,20,15,25]).csp_safe()

Applique ta CSP script-src 'nonce-sp-nonce' et le chart se rend toujours.

VS Code Extension

SeraPlot Live Preview
Live Preview

Official SeraPlot extension for Visual Studio Code — live preview, theme studio, snippets and a chart gallery.

Marketplace: https://marketplace.visualstudio.com/items?itemName=feur25.seraplot-vscode


Install

From the command palette or terminal — no browser needed:

ext install feur25.seraplot-vscode

Or from the Extensions view Ctrl+Shift+X, search SeraPlot:

Open in VS Code Marketplace →
💡 The extension auto-detects your Python environment via seraplot.pythonPath. Works on Windows, macOS and Linux.

Download the .vsix from the GitHub releases page, then install via terminal:

code --install-extension seraplot-vscode-0.6.1.vsix

Or drag the .vsix file directly into the VS Code Extensions panel.

📦 Ideal for air-gapped environments, corporate proxies, or pinning a specific version without going through the Marketplace.

Commands

IDTitleDescription
seraplot.previewSeraPlot: Live PreviewRender every sp.Chart of the current Python file in a side panel and refresh on save
seraplot.themeStudioSeraPlot: Open Theme StudioPick a palette + background, copy the generated sp.set_global_background(...) snippet
seraplot.gallerySeraPlot: Open GalleryBrowse all chart families with thumbnails and one-click code samples

The Live Preview button also appears in the editor title bar for any .py file.


Snippets

PrefixDescription
seraplot-importimport seraplot as sp
seraplot-barMinimal bar chart
seraplot-scatterScatter chart
seraplot-dashboard2x2 grid layout
seraplot-automlsp.auto_classify(...) skeleton
seraplot-driftsp.drift_detect(...) skeleton

Settings

KeyDefaultDescription
seraplot.pythonPathpythonPython interpreter used to render previews
seraplot.autoReloadtrueRe-render on save

Set seraplot.pythonPath to your project venv, e.g. ${workspaceFolder}/.venv/Scripts/python.exe on Windows or ${workspaceFolder}/.venv/bin/python on macOS / Linux.


How the preview works

  1. The active .py file is executed via runpy.run_path in a child Python process using seraplot.pythonPath.
  2. Every sp.Chart instance found in the module globals is exported with sp.export_html(chart).
  3. The HTML is concatenated and rendered inside a VS Code Webview panel.
  4. With seraplot.autoReload = true the panel re-runs automatically when the file is saved.

The preview is sandboxed in a Webview — no network access, no eval. Charts are CSP-safe (see config/csp.md).


Source

Repository: https://github.com/feur25/seraplot — folder seraplot-vscode/.

License: MIT.

Extension officielle SeraPlot pour Visual Studio Code — aperçu en direct, theme studio, snippets et galerie de graphiques.

Marketplace : https://marketplace.visualstudio.com/items?itemName=feur25.seraplot-vscode


Installation

Depuis la palette de commandes ou un terminal — sans navigateur :

ext install feur25.seraplot-vscode

Ou depuis la vue Extensions Ctrl+Shift+X, cherchez SeraPlot :

Ouvrir dans le Marketplace VS Code →
💡 L'extension détecte automatiquement votre environnement Python via seraplot.pythonPath. Fonctionne sur Windows, macOS et Linux.

Téléchargez le .vsix depuis la page des releases GitHub, puis installez via le terminal :

code --install-extension seraplot-vscode-0.6.1.vsix

Ou glissez-déposez le fichier .vsix directement dans le panneau Extensions de VS Code.

📦 Idéal pour les environnements hors ligne, les proxys d'entreprise, ou pour figer une version spécifique sans passer par le Marketplace.

Commandes

IDTitreDescription
seraplot.previewSeraPlot: Live PreviewAffiche tous les sp.Chart du fichier Python courant dans un panneau et rafraîchit à la sauvegarde
seraplot.themeStudioSeraPlot: Open Theme StudioChoisir une palette + un fond, copier le snippet sp.set_global_background(...) généré
seraplot.gallerySeraPlot: Open GalleryParcourir toutes les familles de graphiques avec aperçus et exemples de code en un clic

Le bouton Live Preview apparaît également dans la barre de titre de l'éditeur pour tout fichier .py.


Snippets

PréfixeDescription
seraplot-importimport seraplot as sp
seraplot-barGraphique en barres minimal
seraplot-scatterNuage de points
seraplot-dashboardGrille 2×2
seraplot-automlSquelette sp.auto_classify(...)
seraplot-driftSquelette sp.drift_detect(...)

Paramètres

CléDéfautDescription
seraplot.pythonPathpythonInterpréteur Python utilisé pour les aperçus
seraplot.autoReloadtrueRe-rendu à chaque sauvegarde

Pointer seraplot.pythonPath vers le venv du projet, par exemple ${workspaceFolder}/.venv/Scripts/python.exe sous Windows ou ${workspaceFolder}/.venv/bin/python sous macOS / Linux.


Fonctionnement de l'aperçu

  1. Le fichier .py actif est exécuté via runpy.run_path dans un processus Python enfant utilisant seraplot.pythonPath.
  2. Chaque instance sp.Chart trouvée dans les globales du module est exportée avec sp.export_html(chart).
  3. Le HTML est concaténé et rendu dans un panneau Webview de VS Code.
  4. Avec seraplot.autoReload = true, le panneau se relance automatiquement à chaque sauvegarde du fichier.

L'aperçu est sandboxé dans un Webview — pas d'accès réseau, pas d'eval. Les graphiques sont CSP-safe (voir config/csp.md).


Code source

Dépôt : https://github.com/feur25/seraplot — dossier seraplot-vscode/.

Licence : MIT.

Sera Framework

A native core for plotting, learning, and tabular data.

Sera is the shared architecture behind SeraPlot, SeraML, and the planned SeraDFrame layer. The goal is simple: keep the public API familiar, while moving expensive work into a Rust core that can be reused from Python, JavaScript, and WebAssembly.

RustCore runtime
Python / JSBindings
Local firstDefault mode
PortableArtifacts

Sera is not a separate product that replaces the libraries above it. It is the internal stack that lets each library share the same rendering, algorithm, serialization, and export logic. That keeps the user-facing APIs small while avoiding duplicated implementations between languages.

The framework is designed for documentation, notebooks, local reports, and developer tools where a chart, a model, or a data operation should be fast to produce and easy to ship as a standalone artifact.

Project Layers
LayerResponsibilityTypical outputs
SeraPlotChart construction, rendering, export, and interactive document previews.
HTMLSVGWASMDocs
SeraMLNative machine-learning algorithms with a familiar fit, predict, and export workflow.
Model stateMetricsONNX
SeraDFramePlanned tabular layer for loading, transforming, and passing data between plotting and ML.
TablesSQL-like opsZero-copy paths
How The Stack Fits

The language bindings stay close to the conventions users already know. Python code can feel like a plotting or ML library, JavaScript can focus on browser integration, and the shared Rust core remains responsible for the performance-sensitive work.

Public API
Python functions, JavaScript modules, and future notebook or WASM entry points.
Bindings
Thin adapters that validate inputs, convert data, and call the shared core.
Rust core
Rendering, algorithms, model state, telemetry hooks, exports, and serialization.
Artifacts
Standalone documents, chart payloads, model summaries, and portable runtime data.
Design Notes

What Sera optimizes for

  • Fast local execution without requiring a service backend.
  • Small output files that can be embedded in docs or shared as reports.
  • Predictable APIs across Python, JavaScript, Rust, and WebAssembly.
  • Clear boundaries between user data, generated artifacts, and optional telemetry.

What stays explicit

  • Telemetry remains opt-in and documented separately.
  • Native acceleration is used where it helps, without hiding the data flow.
  • Benchmarks should be read as implementation signals, not as universal guarantees.
  • Experimental surfaces are marked before they become stable API.
Performance Reference

The published ratios describe benchmarked paths where the native implementation removes heavy wrapper overhead. Real-world gains depend on data size, chart type, hardware, and export target.

ComparisonReported ratioInterpretation
SeraPlot vs Plotly6 000xCompact native rendering path for chart generation and export.
SeraPlot vs matplotlib480xLower overhead for common chart construction paths.
SeraPlot vs Seaborn320xLess wrapper work before producing the final artifact.
SeraML vs sklearn KMeans686xOptimized native loops for iterative workloads.
SeraML vs sklearn Random Forest28xParallel training and scoring potential in tree workloads.
Documentation note: this page intentionally avoids marketing buttons. It is meant to explain the architecture first, then point readers to the dedicated product pages from the sidebar.

Sera Framework

Un coeur natif pour les graphiques, le machine learning et les donnees tabulaires.

Sera est l'architecture partagee derriere SeraPlot, SeraML et la future couche SeraDFrame. L'objectif est simple : garder une API familiere, tout en placant le travail couteux dans un coeur Rust reutilisable depuis Python, JavaScript et WebAssembly.

RustCoeur runtime
Python / JSBindings
Local firstMode par defaut
PortableArtifacts

Sera n'est pas un produit separe qui remplace les bibliotheques au-dessus de lui. C'est la pile interne qui permet a chaque bibliotheque de partager le meme rendu, les memes algorithmes, la meme serialisation et les memes exports. L'API reste plus petite, et l'implementation n'est pas dupliquee entre les langages.

Le framework vise les documentations, notebooks, rapports locaux et outils developpeur ou un graphique, un modele ou une operation de donnees doit etre produit rapidement puis partage comme artifact autonome.

Couches Du Projet
CoucheResponsabiliteSorties typiques
SeraPlotConstruction de graphiques, rendu, export et previews interactives dans la documentation.
HTMLSVGWASMDocs
SeraMLAlgorithmes de machine learning natifs avec un workflow familier fit, predict et export.
Etat modeleMetriquesONNX
SeraDFrameCouche tabulaire prevue pour charger, transformer et faire circuler les donnees entre plotting et ML.
TablesOps SQL-likeZero-copy
Organisation De La Pile

Les bindings restent proches des conventions que les utilisateurs connaissent deja. Python peut ressembler a une bibliotheque de plotting ou de ML, JavaScript peut se concentrer sur l'integration navigateur, et le coeur Rust gere le travail sensible aux performances.

API publique
Fonctions Python, modules JavaScript et futurs points d'entree notebook ou WASM.
Bindings
Adaptateurs fins qui valident les entrees, convertissent les donnees et appellent le coeur partage.
Coeur Rust
Rendu, algorithmes, etat modele, hooks telemetry, exports et serialisation.
Artifacts
Documents autonomes, payloads de graphiques, resumes de modeles et donnees runtime portables.
Notes De Conception

Ce que Sera optimise

  • Execution locale rapide sans backend obligatoire.
  • Fichiers de sortie compacts, faciles a integrer dans une doc ou un rapport.
  • APIs previsibles entre Python, JavaScript, Rust et WebAssembly.
  • Frontieres claires entre donnees utilisateur, artifacts generes et telemetry optionnelle.

Ce qui reste explicite

  • La telemetry reste opt-in et documentee sur une page separee.
  • L'acceleration native est utilisee quand elle aide, sans masquer le flux de donnees.
  • Les benchmarks doivent etre lus comme des signaux d'implementation, pas comme des garanties universelles.
  • Les surfaces experimentales sont indiquees avant de devenir une API stable.
Reference Performance

Les ratios publies decrivent des chemins benchmarkes ou l'implementation native retire beaucoup d'overhead. Les gains reels dependent de la taille des donnees, du type de graphique, du materiel et de la cible d'export.

ComparaisonRatio annonceLecture conseillee
SeraPlot vs Plotly6 000xChemin de rendu natif compact pour generer et exporter les graphiques.
SeraPlot vs matplotlib480xMoins d'overhead sur les chemins courants de construction de graphiques.
SeraPlot vs Seaborn320xMoins de couches wrapper avant de produire l'artifact final.
SeraML vs sklearn KMeans686xBoucles natives optimisees pour les workloads iteratifs.
SeraML vs sklearn Random Forest28xPotentiel de parallelisation pour l'entrainement et le scoring des arbres.
Note documentation : cette page evite volontairement les boutons marketing. Elle explique d'abord l'architecture, puis laisse la sidebar guider vers les pages produit dediees.

API Reference

Complete alphabetical index of every public symbol exported by seraplot.

Chart Functions — 2D

FunctionDescription
build_area_chartArea Chart
build_bar_chartBar Chart
build_boxplotBox Plot
build_bubbleBubble Chart
build_bulletBullet Chart
build_candlestickCandlestick Chart
build_donut_chartDonut Chart
build_dumbbellDumbbell Chart
build_funnelFunnel Chart
build_gaugeGauge Chart
build_gridGrid Layout
build_grouped_barGrouped Bar Chart
build_hbarHorizontal Bar Chart
build_heatmapHeatmap
build_histogram_overlayHistogram Overlay
build_histogramHistogram
build_kde_chartKDE Chart
build_line_chartLine Chart
build_lollipop_chartLollipop Chart
build_multiline_chartMulti-Line Chart
build_parallelParallel Coordinates
build_pie_chartPie Chart
build_radar_chartRadar Chart
build_ridgeline_chartRidgeline Chart
build_scatter_chartScatter Chart
build_slideshowSlideshow
build_slopeSlope Chart
build_stacked_barStacked Bar Chart
build_sunburstSunburst Chart
build_treemapTreemap
build_violinViolin Chart
build_waterfallWaterfall Chart
build_wordcloudWord Cloud

Chart Functions — 3D

FunctionDescription
build_bar3d_chartBar Chart 3D
build_bubble3d_chartBubble Chart 3D
build_candlestick3d_chartCandlestick Chart 3D
build_dumbbell3d_chartDumbbell Chart 3D
build_funnel3d_chartFunnel Chart 3D
build_globe3d_chartGlobe 3D
build_heatmap3d_chartHeatmap 3D
build_kde3d_chartKDE Chart 3D
build_line3d_chartLine Chart 3D
build_lollipop3d_chartLollipop Chart 3D
build_pie3d_chartPie Chart 3D
build_radar3d_chartRadar Chart 3D
build_ridgeline3d_chartRidgeline Chart 3D
build_scatter3d_chartScatter 3D
build_stacked_bar3d_chartStacked Bar Chart 3D
build_sunburst3d_chartSunburst Chart 3D
build_violin3d_chartViolin Chart 3D

Chart Functions — Map

FunctionDescription
build_bubble_mapBubble Map
build_choroplethChoropleth Map

Machine Learning

FunctionDescription
dbscan-classDBSCAN Class
build_dbscan_chartDBSCAN Chart
build_dbscan_chart_3dDBSCAN 3D Chart

Configuration

FunctionDescription
set_auto_displayAuto Display (Jupyter)
backgroundBackground Configuration
build_hover_jsonCustom Hover Tooltips
palettePalette & Colors

Index alphabétique complet de tous les symboles publics exportés par seraplot.


Fonctions graphiques — 2D

FonctionDescription
build_area_chartGraphique en aire
build_bar_chartGraphique en barres
build_boxplotBoîte à moustaches
build_bubbleGraphique à bulles
build_bulletGraphique bullet
build_candlestickGraphique en bougie
build_donut_chartGraphique en anneau
build_dumbbellGraphique haltère
build_funnelGraphique en entonnoir
build_gaugeJauge
build_gridGrille de graphiques
build_grouped_barBarres groupées
build_hbarBarres horizontales
build_heatmapCarte de chaleur
build_histogram_overlayHistogramme superposé
build_histogramHistogramme
build_kde_chartEstimation par noyau
build_line_chartGraphique en courbe
build_lollipop_chartGraphique en sucette
build_multiline_chartCourbes multiples
build_parallelCoordonnées parallèles
build_pie_chartCamembert
build_radar_chartGraphique radar
build_ridgeline_chartRidgeline
build_scatter_chartNuage de points
build_slideshowDiaporama
build_slopeGraphique de pente
build_stacked_barBarres empilées
build_sunburstSunburst
build_treemapTreemap
build_violinGraphique en violon
build_waterfallCascade
build_wordcloudNuage de mots

Fonctions graphiques — 3D

FonctionDescription
build_bar3d_chartBarres 3D
build_bubble3d_chartBulles 3D
build_candlestick3d_chartBougie 3D
build_dumbbell3d_chartHaltère 3D
build_funnel3d_chartEntonnoir 3D
build_globe3d_chartGlobe 3D
build_heatmap3d_chartCarte de chaleur 3D
build_kde3d_chartEstimation par noyau 3D
build_line3d_chartCourbe 3D
build_lollipop3d_chartSucette 3D
build_pie3d_chartCamembert 3D
build_radar3d_chartRadar 3D
build_ridgeline3d_chartRidgeline 3D
build_scatter3d_chartNuage de points 3D
build_stacked_bar3d_chartBarres empilées 3D
build_sunburst3d_chartSunburst 3D
build_violin3d_chartViolon 3D

Fonctions graphiques — Carte

FonctionDescription
build_bubble_mapCarte à bulles
build_choroplethChoropleth

Machine Learning

FonctionDescription
dbscan-classClasse DBSCAN
build_dbscan_chartGraphique DBSCAN
build_dbscan_chart_3dGraphique DBSCAN 3D

Configuration

FonctionDescription
set_auto_displayAffichage automatique (Jupyter)
backgroundConfiguration du fond
build_hover_jsonInfobulles personnalisées
palettePalette & Couleurs

About & Support

👨‍💻

A solo project

SeraPlot is built entirely on my own, on top of a day job. I regularly rework the core of the framework to keep improving it — not because I'm the best at low-level optimisation, but because I care about delivering a complete solution that originally answered my own needs and hopefully answers yours too.

Ultra-performant Fully customisable Complete

Get in touch

✉️ Email only

If you'd like a specific mechanic, feature or chart type, don't hesitate to reach out — by email only. I can't promise I'll build everything, but I'll do as much as I can.

📧 feur09@gmail.com

Support the project

☕ Buy me a coffee

I work on SeraPlot for free, on top of my day job. If it saves you time, a donation is very welcome — but you absolutely don't need to donate to send me a feature request.

Donate via PayPal

Thanks for using SeraPlot ✨

👨‍💻

Un projet en solo

SeraPlot est entièrement réalisé seul, en plus d'un travail à plein temps. Je retravaille régulièrement le corps du framework pour continuer à l'améliorer — pas parce que je suis le meilleur en optimisation bas-niveau, mais parce que je tiens à offrir une solution complète qui répondait au départ à mes propres besoins et qui répond, j'espère, aussi aux vôtres.

Ultra-performant Entièrement personnalisable Complet

Me contacter

✉️ Par mail uniquement

Si vous voulez une mécanique, une fonctionnalité ou un type de graphique particulier, n'hésitez pas — par mail exclusivement. Je ne dis pas que je serai en capacité de tout réaliser, mais je ferai le plus possible.

📧 feur09@gmail.com

Soutenir le projet

☕ Offrez-moi un café

Je travaille sur SeraPlot gratuitement, en plus de mon travail. Si cela vous fait gagner du temps, un don est le bienvenu — mais il n'y a aucun besoin de faire un don pour me faire une demande de fonctionnalité.

Soutenir via PayPal

Merci d'utiliser SeraPlot ✨