Scatter Plot
Basic Plot with Multiple Display Modes
Set markers to points, line, or line+points; series and gear controls expose styling.
Axis ranges preserve automatic endpoints: { range: [50, null] } fixes the minimum while the maximum follows changing data. Clearing either range input restores automatic sizing for that endpoint. “Restore initial values” returns the section to the values it mounted with; “Reset to defaults” uses the shipped defaults.
styles contains sparse overrides for the selected series and supports bind:styles. Controls show authored styles until a field is overridden. “Clear style overrides” removes those edits and reveals the authored styles again, including when an explicit override equals a shipped default.
Interactive example
svelte<script lang="ts">
import { type InternalPoint, ScatterPlot } from 'matterviz'
const make_series = (label: string, id_prefix: string, y: number[], point_style) => ({
x: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
y,
point_style,
label,
metadata: y.map((_, idx) => ({ id: `${id_prefix}${idx + 1}`, series_label: label })),
})
const basic_data = make_series(`Basic Data`, `P`, [5, 7, 2, 8, 4, 9, 3, 6, 8, 5], {
fill: `steelblue`,
radius: 5,
})
const second_series = make_series(`Second Series`, `S`, [2, 4, 6, 3, 7, 5, 8, 4, 6, 9], {
fill: `orangered`,
radius: 4,
})
// Currently selected display mode
let display_mode = $state('line+points')
let clicked_point_info = $state('No point clicked yet.')
let double_clicked_point_info = $state('No point double-clicked yet.')
let hovered_point_info = $state('No point hovered yet.')
type PointMeta = { id?: string; series_label?: string }
const describe = (verb: string, point: InternalPoint<PointMeta>): string => {
const { x: coord_x, y: coord_y, metadata, series_idx, point_idx } = point
const series_label =
metadata?.series_label ?? (series_idx === 0 ? basic_data.label : second_series.label)
const id = metadata ? `, Metadata ID: ${metadata.id}` : ``
return `${verb}: Point (${coord_x}, ${coord_y}), Series: '${series_label}', Point Index: ${point_idx}${id}`
}
const on_point_click = ({ point }: { point: InternalPoint<PointMeta> }): void => {
clicked_point_info = describe(`Clicked`, point)
}
const handle_point_double_click = ({ point }: { point: InternalPoint<PointMeta> }): void => {
double_clicked_point_info = describe(`Double-clicked`, point)
}
const handle_point_hover = (payload: { point: InternalPoint<PointMeta> | null } | null) => {
const point = payload?.point
hovered_point_info = point ? describe(`Hovering`, point) : `No point hovered yet.`
}
</script>
<label style="margin-bottom: 1em; display: block">
Display Mode:
<select bind:value={display_mode}>
{#each [['points', 'Points only'], ['line', 'Lines only'], ['line+points', 'Lines and Points']] as [value, label] (value)}
<option {value}>{label}</option>
{/each}
</select>
</label>
<ScatterPlot
series={[
{ ...basic_data, markers: display_mode },
{ ...second_series, markers: display_mode },
]}
x_axis={{ label: 'X Axis' }}
y_axis={{ label: 'Y Value' }}
point_events={{ onclick: on_point_click, ondblclick: handle_point_double_click }}
on_point_hover={handle_point_hover}
style="height: 300px"
/>
<p>{clicked_point_info}</p>
<p>{double_clicked_point_info}</p>
<p>{hovered_point_info}</p>Marginal Distributions
Marginal distribution plots summarize the data projected onto each axis as a thin strip alongside the plot. The marginals prop is a layered API: pass a boolean for sensible defaults, a single type string, or a per-side map for full control. Built-in types are histogram, kde, cdf, and rug, plus a snippet escape hatch for anything else. Marginals reuse the main plot’s positional scale, so they stay pixel-aligned and update live with zoom/pan. The same marginals API works on every 2D plot (Histogram, BarPlot, BoxPlot, BinnedScatterPlot).
The example below combines the common controls: per-side type, per_series (one curve per series vs. one merged curve), and placement (auto hugs tick-free sides like top/right and sits outside the ticks on axis sides; force flush/outer).
Interactive example
svelte<script>
import { ScatterPlot } from 'matterviz'
import { box_muller, seeded_rng } from '#site/histogram-data.js'
// deterministic gaussian clusters (seeded rng keeps the demo stable)
const rng = seeded_rng(7)
const normal = (mean, std_dev) => box_muller(mean, std_dev, rng)
const cluster = (count, mean_x, mean_y, std_dev, fill, label) => ({
x: Array.from({ length: count }, () => normal(mean_x, std_dev)),
y: Array.from({ length: count }, () => normal(mean_y, std_dev)),
markers: 'points', // scattered clusters: no connecting lines
point_style: { fill, radius: 3, fill_opacity: 0.55 },
label,
})
const series = [
cluster(250, 2, 3, 1, 'steelblue', 'Cluster A'),
cluster(250, 5, 6, 1.2, 'orangered', 'Cluster B'),
]
const types = ['histogram', 'kde', 'cdf', 'rug']
let top_type = $state('histogram')
let right_type = $state('kde')
let per_series = $state(true)
let placement = $state('auto')
</script>
<div class="demo-controls">
<label
>Top:
<select bind:value={top_type}
>{#each types as marginal_type (marginal_type)}<option>{marginal_type}</option
>{/each}</select
>
</label>
<label
>Right:
<select bind:value={right_type}
>{#each types as marginal_type (marginal_type)}<option>{marginal_type}</option
>{/each}</select
>
</label>
<label
>Placement:
<select bind:value={placement}>
<option>auto</option><option>flush</option><option>outer</option>
</select>
</label>
<label><input type="checkbox" bind:checked={per_series} /> per-series</label>
</div>
<ScatterPlot
{series}
marginals={{
top: { type: top_type, per_series, placement, size: 80 },
right: { type: right_type, per_series, placement, size: 80 },
}}
style="height: 480px"
/>More options
Each strip is fully configurable via per-side keys (shown as static snippets):
- Style & bin a strip:
size,gap,fill,fill_opacity,stroke,stroke_width,opacity, histogrambins, KDEbandwidth('silverman'/'scott'/number), linecurve. - Normalize histograms:
normalize: 'count' | 'density' | 'probability'. - Align two strips by pinning the value axis:
value_range: [0, 1]. - Bind a strip to a secondary axis:
axis: 'x2' | 'y2'. - Summarize external values instead of the series:
data: number[] | (ctx) => number[]. - Compute a bespoke curve:
reduce: (values, weights, ctx) => MarginalCurve.
<ScatterPlot
{series}
marginals={{
top: { type: 'histogram', bins: 40, fill: '#0ca678', normalize: 'density' },
right: { type: 'kde', bandwidth: 'scott', curve: 'natural' },
}}
/>
For anything the built-ins don’t cover, a per-side snippet draws the strip from scratch. It receives { rect, positional_scale, value_scale, baseline, curves, series }:
{#snippet mean_marker(ctx)}
{#each ctx.series as srs (srs.label)}
{@const x_values = Array.from(srs.x ?? [])}
{@const mean = x_values.reduce((sum, val) => sum + val, 0) / (x_values.length || 1)}
<circle cx={ctx.positional_scale(mean)} cy={ctx.rect.y + 10} r="3" fill={srs.color} />
{/each}
{/snippet}
<ScatterPlot {series} marginals={{ top: { snippet: mean_marker } }} />
Density Contours
Dense point clouds (e.g. parity plots of predicted vs. reference energies) hide where most points actually sit. density_contours draws Gaussian kernel density contours under each series’ markers. Levels are iso-proportions: the 0.5 contour bounds the densest region holding half of a series’ estimated density, so levels compare across series of different sizes and stay put while panning (zoomed far enough in, they become fractions of the density in view). The density is estimated in screen space with a bandwidth in px, so the contours follow log axes and pan/zoom like the markers do. Use filled for stacked translucent bands and levels for the count or explicit fractions.
Interactive example
svelte<script>
import { ScatterPlot } from 'matterviz'
// seeded parity data: two models' predicted vs. reference formation energies
let seed = 3
const rand = () => (seed = (seed * 16807) % 2147483647) / 2147483647
const normal = () => Math.sqrt(-2 * Math.log(rand())) * Math.cos(2 * Math.PI * rand())
const model = (count, bias, noise, fill, label) => {
const ref = Array.from({ length: count }, () => -1.5 + 0.9 * normal())
return {
x: ref,
y: ref.map((val) => val + bias + noise * normal() * (1 + 0.4 * Math.abs(val))),
markers: `points`,
point_style: { fill, radius: 1.5, fill_opacity: 0.35, stroke_width: 0 },
label,
}
}
const series = [
model(3000, 0, 0.12, `steelblue`, `Model A`),
model(3000, 0.15, 0.3, `orangered`, `Model B`),
]
let filled = $state(true)
let show_points = $state(true)
let n_levels = $state(4)
let bandwidth = $state(15)
</script>
<div class="demo-controls">
<label><input type="checkbox" bind:checked={filled} /> filled</label>
<label><input type="checkbox" bind:checked={show_points} /> points</label>
<label>levels <input type="range" min="1" max="12" bind:value={n_levels} /> {n_levels}</label
>
<label
>bandwidth <input type="range" min="4" max="40" bind:value={bandwidth} />
{bandwidth} px</label
>
</div>
<ScatterPlot
{series}
styles={{ show_points }}
density_contours={{ filled, levels: n_levels, bandwidth }}
ref_lines={[{ type: `diagonal`, slope: 1, intercept: 0, style: { dash: `4 4` } }]}
x_axis={{ label: `E<sub>form</sub> reference`, unit: `eV/atom` }}
y_axis={{ label: `E<sub>form</sub> predicted`, unit: `eV/atom` }}
style="height: 450px"
/>Bubble Size Legend
When markers are sized by size_values, ScatterPlot adds a size legend that maps a few round values to the marker radii they get. Like the color bar, the plot places it clear of the data. Pass size_legend={{ title, count, values, format }} to configure it, wrapper_style to pin it, or null to hide it.
Interactive example
svelte<script>
import { ScatterPlot } from 'matterviz'
let seed = 11
const rand = () => (seed = (seed * 16807) % 2147483647) / 2147483647
const n_atoms = Array.from({ length: 60 }, () => Math.round(2 + 118 * rand() ** 2))
const series = [
{
x: n_atoms.map(() => 2 + 6 * rand()),
y: n_atoms.map((count) => Math.max(0, 6 - Math.log2(count) * 0.6 + rand())),
size_values: n_atoms,
markers: `points`,
point_style: { fill: `teal`, fill_opacity: 0.5 },
label: `Materials`,
},
]
</script>
<ScatterPlot
{series}
size_scale={{ radius_range: [3, 22] }}
size_legend={{ title: `Atoms per cell` }}
x_axis={{ label: `Density`, unit: `g/cm³` }}
y_axis={{ label: `Band gap`, unit: `eV` }}
style="height: 420px"
/>Line Interpolation Curves
The connecting line between points chooses its interpolation via line_style.curve. The default monotone smooths through points, while linear draws perfectly straight segments (usually the better choice for scientific data: no spline overshoot between samples). Toggle the curve below on a deliberately sharp signal to see the difference:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// sharp zigzag so the interpolation style is unmistakable
const coord_x = Array.from({ length: 11 }, (_, idx) => idx)
const coord_y = [0, 8, 1, 9, 2, 7, 1, 8, 0, 6, 2]
const curves = ['linear', 'monotone', 'natural', 'step', 'basis', 'catmull-rom']
let curve = $state('linear')
let series = $derived([
{
x: coord_x,
y: coord_y,
point_style: { fill: 'steelblue', radius: 4 },
line_style: { curve },
markers: 'line+points',
label: `curve: ${curve}`,
},
])
</script>
<div class="demo-controls">
<label>
Connecting line curve:
<select bind:value={curve}>
{#each curves as option (option)}
<option value={option}>{option}</option>
{/each}
</select>
</label>
</div>
<ScatterPlot {series} x_axis={{ label: 'x' }} y_axis={{ label: 'y' }} style="height: 300px" />Custom Point Styling and Tooltips
Point styles, custom tooltips, and hover effects:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
const x_values = Array.from({ length: 10 }, (_, idx) => idx + 1)
// One row of points per style at height y; tooltips read the series name from metadata
const style_row = (y: number, label: string, point_style, point_hover) => ({
x: x_values,
y: x_values.map(() => y),
point_style,
point_hover,
label,
metadata: x_values.map(() => ({ series_name: label })),
})
const series_with_styles = [
// Extra large red points with thick border
style_row(
10,
`Giant red`,
{ fill: `crimson`, radius: 12, stroke: `darkred`, stroke_width: 3 },
{ scale: 1.3, stroke: `gold`, stroke_width: 4 },
),
// Medium green semi-transparent points with dramatic hover effect (2.5x larger)
style_row(
8,
`Growing green`,
{
fill: `mediumseagreen`,
radius: 8,
fill_opacity: 0.6,
stroke: `green`,
stroke_width: 1,
},
{ scale: 2.5, stroke: `lime`, stroke_width: 2 },
),
// Outline-only points (hollow) with color change on hover
style_row(
6,
`Color-changing hollow`,
{ fill: `purple`, fill_opacity: 0.4, radius: 6, stroke: `indigo`, stroke_width: 2 },
{ scale: 1.8, stroke: `magenta`, stroke_width: 3 },
),
// Tiny points with extreme hover growth
style_row(
4,
`Exploding dots`,
{ fill: `orange`, radius: 3 },
{ scale: 4, stroke: `red`, stroke_width: 2 },
),
// Extremely small dots whose wide hover stroke creates a glow effect
style_row(
2,
`Glowing microdots`,
{ fill: `dodgerblue`, radius: 1.5, stroke: `transparent`, stroke_width: 0 },
{ scale: 6, stroke: `cyan`, stroke_width: 8 },
),
]
</script>
<ScatterPlot
series={series_with_styles.map((srs) => ({ ...srs, markers: 'points' }))}
x_axis={{ label: 'X Axis' }}
y_axis={{ label: 'Point Style Examples', range: [0, 12] }}
style="height: 400px"
>
{#snippet tooltip({ x: coord_x, y: coord_y, metadata })}
<strong>{metadata.series_name}</strong>
Point at ({coord_x}, {coord_y})
{/snippet}
</ScatterPlot>Per-Point Custom Styling with Marker Symbols and Sizing
Per-point styles, sizes, and marker symbols in one series. Point size follows distance from the spiral center via size_values.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
import { symbol_names } from 'matterviz/labels'
let show_labels = $state(true)
let label_size = $state(14)
let size_scale = $state({ radius_range: [2, 15], type: 'linear' }) // [min_radius, max_radius]
const n_points = 40
// Spiral of growing radius, color changing gradually and marker type cycling along it
const spiral = Array.from({ length: n_points }, (_, idx) => {
const [angle, radius] = [idx * 0.5, 1 + idx * 0.3]
return { angle, radius, x: Math.cos(angle) * radius, y: Math.sin(angle) * radius }
})
const spiral_data = {
x: spiral.map((pt) => pt.x),
y: spiral.map((pt) => pt.y),
size_values: spiral.map((pt) => pt.radius), // Use spiral radius for sizing
metadata: spiral.map(({ angle, radius }) => ({ angle, radius })),
point_style: spiral.map((_, idx) => ({
fill: `hsl(${(idx / n_points) * 360}, 80%, 50%)`,
stroke: 'white',
stroke_width: 1 + idx / 20, // Gradually thicker stroke
symbol_type: symbol_names[idx % symbol_names.length],
radius: 5,
})),
}
let point_label = $derived(
show_labels
? spiral.map((_, idx) => ({
text: `P${idx}`,
offset: { x: 10 },
font_size: `${label_size}px`,
}))
: [],
)
</script>
<div class="demo-controls">
<label>
Label Size: {label_size}
<input type="range" bind:value={label_size} min="8" max="20" />
</label>
<label>
<input type="checkbox" bind:checked={show_labels} />
Show Labels
</label>
<label>
Max Size (px):
<input
type="number"
bind:value={size_scale.radius_range[1]}
min="5"
max="30"
step="1"
style="width: 50px"
/>
</label>
<label>
Size Scale:
<select bind:value={size_scale.type}>
<option value="linear">Linear</option>
<option value="log">Log</option>
</select>
</label>
</div>
<ScatterPlot
series={[{ ...spiral_data, point_label, markers: 'points' }]}
x_axis={{ label: 'X Axis', range: [-15, 15] }}
y_axis={{ label: 'Y Axis', range: [-15, 15] }}
{size_scale}
style="height: 500px"
>
{#snippet tooltip({ x: coord_x, y: coord_y, metadata })}
<strong>Spiral Point</strong><br />
Position: ({coord_x.toFixed(2)}, {coord_y.toFixed(2)})<br />
Angle: {metadata.angle.toFixed(2)} rad<br />
Value (Radius): {metadata.radius.toFixed(2)}
{/snippet}
</ScatterPlot>Categorized Data and Custom Axis Tick Intervals
Categorized data with color coding, custom tick intervals, and negative values:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
const categories = ['Category A', 'Category B', 'Category C', 'Category D']
const category_colors = ['crimson', 'royalblue', 'goldenrod', 'mediumseagreen']
// 40 points in random categories across positive and negative space (-10 to 10)
const sample_data = Array.from({ length: 40 }, () => {
const category_idx = Math.floor(Math.random() * categories.length)
return {
x: Math.random() * 20 - 10,
y: Math.random() * 20 - 10,
category: categories[category_idx],
color: category_colors[category_idx],
}
})
// Group data by category to create series
const series_data = categories.map((category, idx) => {
const points = sample_data.filter((point) => point.category === category)
return {
x: points.map((point) => point.x),
y: points.map((point) => point.y),
point_style: {
fill: category_colors[idx],
radius: 6 - idx, // Size varies by category
stroke: 'black',
stroke_width: 0.5,
},
metadata: points.map((point) => ({ category: point.category, color: point.color })),
label: category,
}
})
const ticks = $state({ x: -5, y: -5 }) // Tick interval settings
</script>
<div class="demo-controls">
{#each Object.keys(ticks) as axis (axis)}
<label>
{axis} Tick Interval:
<select bind:value={ticks[axis]}>
{#each [2, 5, 10] as num (num)}
<option value={-num}>{num} units</option>
{/each}
</select>
</label>
{/each}
</div>
<ScatterPlot
series={series_data.map((srs) => ({ ...srs, markers: 'points' }))}
x_axis={{ label: 'X Value', range: [-15, 15], ticks: ticks.x }}
y_axis={{ label: 'Y Value', range: [-15, 15], ticks: ticks.y }}
style="height: 400px;"
>
{#snippet tooltip({ x: coord_x, y: coord_y, metadata })}
<strong>{metadata.category}</strong><br />
Position: ({coord_x.toFixed(2)}, {coord_y.toFixed(2)})
{/snippet}
</ScatterPlot>
<!-- Legend -->
<div class="legend">
{#each categories as category, idx (category)}
<span style:--color={category_colors[idx]}>{category}</span>
{/each}
</div>Time-Based Data with Custom Formatting
Time on the x-axis with custom formatting. tick_label.inside puts tick labels inside the plot for a tighter layout.
Date labels are the classic case for tick rotation: pick the YYYY-MM-DD format and raise the tick count until the labels stop fitting side by side. They tilt to the shallowest angle that keeps them apart (and the plot area shrinks to make room) rather than overlapping. rotation: 0 opts out and keeps them upright:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Dates for the past 30 days
const dates = Array.from({ length: 30 }, (_, idx) => {
const date = new Date()
date.setDate(date.getDate() - (30 - idx))
return date.getTime()
})
// Random values: Series A in [0, 100], Series B in [30, 100]
const time_series = [
[`Series A`, `steelblue`, 0],
[`Series B`, `orangered`, 30],
].map(([label, fill, min]) => ({
x: dates,
y: dates.map(() => min + Math.random() * (100 - min)),
point_style: { fill, radius: 4 },
label,
metadata: dates.map((_, idx) => ({ series: label, day: idx })),
}))
// Format options
let date_format = $state('%Y-%m-%d')
let y_format = $state('.1f')
let inside = $state(false)
let n_ticks = $state(7)
let rotation = $state('auto')
</script>
<div class="demo-controls">
<label>
Date Format:
<select bind:value={date_format}>
{#each [['%b %d', 'Month Day (Jan 01)'], ['%Y-%m-%d', 'YYYY-MM-DD'], ['%d/%m', 'DD/MM']] as [value, label] (value)}
<option {value}>{label}</option>
{/each}
</select>
</label>
<label>
Y-Value Format:
<select bind:value={y_format}>
{#each [['.1f', '1 decimal'], ['.2f', '2 decimals'], ['d', 'Integer']] as [value, label] (value)}
<option {value}>{label}</option>
{/each}
</select>
</label>
<label>
Date Ticks: {n_ticks}
<input type="range" bind:value={n_ticks} min="3" max="20" style="width: 100px" />
</label>
<label>
Rotation:
<select bind:value={rotation}>
{#each ['auto', 0, -45, 90] as angle (angle)}
<option value={angle}>{angle === 'auto' ? 'auto' : `${angle}°`}</option>
{/each}
</select>
</label>
<label>
<input type="checkbox" bind:checked={inside} />
Tick Labels Inside
</label>
</div>
<ScatterPlot
series={time_series.map((srs) => ({ ...srs, markers: 'line+points' }))}
x_axis={{
scale_type: 'time',
format: date_format,
ticks: n_ticks,
label: 'Date',
tick_label: { inside, rotation },
}}
y_axis={{ format: y_format, ticks: 5, label: 'Value', tick_label: { inside } }}
style="height: 350px"
legend={{
layout: `horizontal`,
layout_tracks: 3,
style: `max-width: none; justify-content: center;`,
}}
>
{#snippet tooltip({ x: coord_x, y: coord_y, x_formatted, y_formatted, metadata })}
<strong>{metadata?.series}</strong><br />
Date: {x_formatted}<br />
Value: {y_formatted}
{/snippet}
</ScatterPlot>Points with Shared Coordinates
Points that share coordinates stay separately identifiable and interactive:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Create points with shared X or Y coordinates
const shared_coords_data = {
x: [5, 5, 5, 5, 5, 1, 2, 3, 4, 5, 7, 8, 9, 7, 9],
y: [1, 2, 3, 4, 5, 3, 3, 3, 3, 3, 1, 2, 3, 4, 5],
point_style: { fill: 'steelblue', radius: 6 },
// Add distinct metadata for each point to identify them
metadata: [
// Vertical line points
{ id: 'v1', label: 'V1 (5,1)' },
{ id: 'v2', label: 'V2 (5,2)' },
{ id: 'v3', label: 'V3 (5,3)' },
{ id: 'v4', label: 'V4 (5,4)' },
{ id: 'v5', label: 'V5 (5,5)' },
// Horizontal line points
{ id: 'h1', label: 'H1 (1,3)' },
{ id: 'h2', label: 'H2 (2,3)' },
{ id: 'h3', label: 'H3 (3,3)' },
{ id: 'h4', label: 'H4 (4,3)' },
{ id: 'h5', label: 'H5 (5,3)' },
// Random points
{ id: 'r1', label: 'R1 (7,1)' },
{ id: 'r2', label: 'R2 (8,2)' },
{ id: 'r3', label: 'R3 (9,3)' },
{ id: 'r4', label: 'R4 (7,4)' },
{ id: 'r5', label: 'R5 (9,5)' },
],
}
</script>
<ScatterPlot
series={[shared_coords_data]}
x_axis={{ range: [0, 10], ticks: 1, label: 'X Axis' }}
y_axis={{ range: [0, 6], ticks: 1, label: 'Y Axis' }}
style="height: 350px"
>
{#snippet tooltip({ x: coord_x, y: coord_y, metadata })}
{@const { label, id: identifier } = metadata}
<strong>{label}</strong><br />
Coordinates: ({coord_x}, {coord_y})<br />
ID: {identifier}
{/snippet}
</ScatterPlot>Text Annotations for Scatter Points
Permanent text labels on scatter points:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Data with text labels
const data = {
x: [1, 3, 5, 7, 9],
y: [2, 5, 3, 7, 4],
point_style: { fill: 'steelblue', radius: 6 },
// Add text labels to each point
point_label: [
{ text: 'Point A', offset: { y: -15 } },
{ text: 'Point B', offset: { y: 15 } },
{ text: 'Point C', offset: { y: -15 } },
{ text: 'Point D', offset: { y: -15 } },
{ text: 'Point E', offset: { y: 15 } },
],
}
</script>
<ScatterPlot
series={[{ ...data, markers: 'points' }]}
x_axis={{ label: 'X Axis', range: [0, 10] }}
y_axis={{ label: 'Y Axis', range: [0, 10] }}
style="height: 350px"
/>Different Label Positions
You can position labels in different directions relative to each point:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
const position_data = {
x: [5, 5, 5, 5, 5],
y: [1, 2, 3, 4, 5],
point_style: { fill: 'goldenrod', radius: 5 },
// Different positions for labels
point_label: [
{ text: 'Above', offset: { y: -15, x: 0 } },
{ text: 'Right', offset: { x: 15, y: 0 } },
{ text: 'Below', offset: { y: 15, x: 0 } },
{ text: 'Left', offset: { x: -30, y: 0 } },
{ text: 'Diagonal', offset: { x: 10, y: -10 } },
],
}
</script>
<ScatterPlot
series={[{ ...position_data, markers: 'points' }]}
x_axis={{ label: 'X Axis', range: [0, 10] }}
y_axis={{ label: 'Y Axis', range: [0, 6] }}
style="height: 350px"
/>Interactive Log-Scaled Axes
Log scales for data spanning many orders of magnitude. Use the checkboxes to switch X and Y between linear and log; power laws become straight lines on a log-log plot. Log axes draw unlabeled minor ticks at 2-9 × each decade (thinned over many decades); set minor_ticks: false on an axis to hide them.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
import * as math from 'matterviz/math'
// y clamped to a small positive value so log scales never see 0, also sizing the points
const make_series = (label, fill, x_vals, y_fn) => {
const y = x_vals.map((x_val) => Math.max(y_fn(x_val), math.LOG_EPS))
const metadata = x_vals.map(() => ({ series: label }))
return { x: x_vals, y, size_values: y, point_style: { fill }, label, metadata }
}
const linspace = (count, start, stop) =>
Array.from({ length: count }, (_, idx) => start + (idx / (count - 1)) * (stop - start))
// x from 0.1 to 1000 in quarter-decade steps
const quarter_decades = linspace(17, -1, 3).map((exp) => 10 ** exp)
const all_series = [
make_series(
`Exponential Decay`,
`coral`,
linspace(50, 0.1, 10.1),
(x_val) => 10000 * Math.exp(-0.5 * x_val),
),
// log-spaced x from 0.1 to 1000, more points for a smoother curve
make_series(
`Log Sine Wave`,
`deepskyblue`,
linspace(100, -1, 3).map((exp) => 10 ** exp),
(x_val) => 500 + 400 * Math.sin(Math.log10(x_val) * 5),
),
make_series(`y = x^2`, `mediumseagreen`, quarter_decades, (x_val) => x_val ** 2),
make_series(`y = x^0.5`, `purple`, quarter_decades, (x_val) => x_val ** 0.5),
]
// State for controlling scale types
let x_is_log = $state(false)
let y_is_log = $state(false)
// State for size controls
let size_scale = $state({
radius_range: [2, 8],
type: 'linear',
value_range: [1, 1000],
})
// Derived scale types based on state
let x_scale_type = $derived(x_is_log ? `log` : `linear`)
let y_scale_type = $derived(y_is_log ? `log` : `linear`)
// Reactive limits based on scale type to avoid log(0) issues and accommodate data
let x_range = $derived(x_is_log ? [0.1, 1000] : [null, 1000])
let y_range = $derived(y_is_log ? [0.1, 10000] : [null, 10000])
</script>
<div class="demo-controls">
<label>
<input type="checkbox" bind:checked={x_is_log} />
Log X-Axis
</label>
<label>
<input type="checkbox" bind:checked={y_is_log} />
Log Y-Axis
</label>
</div>
<div class="demo-controls">
<label>
Min Size (px):
<input
type="number"
bind:value={size_scale.radius_range[0]}
min="0.5"
max="10"
step="0.5"
style="width: 50px"
/>
</label>
<label>
Max Size (px):
<input
type="number"
bind:value={size_scale.radius_range[1]}
min="5"
max="30"
step="1"
style="width: 50px"
/>
</label>
<label>
Size Scale:
<select bind:value={size_scale.type}>
<option value="linear">Linear</option>
<option value="log">Log</option>
</select>
</label>
</div>
<ScatterPlot
series={all_series.map((srs) => ({ ...srs, markers: 'line+points' }))}
x_axis={{
scale_type: x_scale_type,
range: x_range,
label: `X Axis (${x_scale_type})`,
format: '~s',
}}
y_axis={{
scale_type: y_scale_type,
range: y_range,
label: `Y Axis (${y_scale_type})`,
format: '~s',
}}
{size_scale}
style="height: 400px"
>
{#snippet tooltip({ x: coord_x, y: coord_y, x_formatted, y_formatted, metadata })}
<strong>{metadata.label ?? metadata.series}</strong><br />
X: {x_formatted || coord_x.toPrecision(3)}<br />
Y: {y_formatted || coord_y.toPrecision(3)}
{/snippet}
</ScatterPlot>Derived Secondary Axis
x2_axis.derive = { forward, inverse } labels the top axis with a function of the bottom one, no extra series needed. Ticks are nice values of the derived quantity, placed where inverse maps them, so decreasing maps like photon energy to wavelength work too. Pick a pair below.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
const hc = 1239.84198 // eV nm
const cu_ka = 1.5406 // Å
const examples = {
'Energy → wavelength': {
x: { label: `Photon energy (eV)`, range: [1.5, 6] },
x2: {
label: `Wavelength (nm)`,
derive: { forward: (energy) => hc / energy, inverse: (nm) => hc / nm },
},
// two Gaussian absorption bands
curve: (energy) =>
Math.exp(-(((energy - 2.4) / 0.25) ** 2)) +
0.6 * Math.exp(-(((energy - 4.6) / 0.4) ** 2)),
y_label: `Absorbance`,
},
'2θ → d-spacing (Cu Kα)': {
x: { label: `2θ (°)`, range: [15, 90] },
x2: {
label: `d (Å)`,
derive: {
forward: (two_theta) => cu_ka / (2 * Math.sin((two_theta * Math.PI) / 360)),
inverse: (d_spacing) => (360 / Math.PI) * Math.asin(cu_ka / (2 * d_spacing)),
},
},
curve: (two_theta) =>
[28.4, 47.3, 56.1, 69.1, 76.4, 88.0].reduce(
(sum, peak, idx) =>
sum + Math.exp(-(((two_theta - peak) / 0.3) ** 2)) / (1 + idx / 2),
0,
),
y_label: `Intensity`,
},
}
let selected = $state(`Energy → wavelength`)
const example = $derived(examples[selected])
const series = $derived.by(() => {
const [lo, hi] = example.x.range
const x = Array.from({ length: 300 }, (_, idx) => lo + ((hi - lo) * idx) / 299)
return [{ x, y: x.map(example.curve), markers: `line`, label: example.y_label }]
})
</script>
<select bind:value={selected}>
{#each Object.keys(examples) as name (name)}
<option value={name}>{name}</option>
{/each}
</select>
<ScatterPlot
{series}
x_axis={example.x}
x2_axis={example.x2}
y_axis={{ label: example.y_label }}
legend={null}
style="height: 400px"
/>Arcsinh Scale: Handling Negative Values and Wide Ranges
Use scale_type='arcsinh' or { type: 'arcsinh', threshold } for signed wide-range axes.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
import { seeded_rng } from '#site/histogram-data.js'
const scale_types = [`linear`, `log`, `arcsinh`]
// scale type per dimension, each with the log warning shown when its data has values <= 0
const dims = $state(
[
{ key: `x`, legend: `X Axis`, effect: `Points with x ≤ 0 will not render` },
{ key: `y`, legend: `Y Axis`, effect: `Points with y ≤ 0 will not render` },
{
key: `color_values`,
legend: `Color`,
effect: `Color mapping may fail for those points`,
},
].map((dim) => ({ ...dim, type: `arcsinh` })),
)
let arcsinh_threshold = $state(10)
// Formation energy-like data: clusters at different orders of magnitude (1, 10, 100, 1000)
const rng = seeded_rng(42)
const values = { x: [], y: [], color_values: [] }
const metadata = []
for (let idx = 0; idx < 80; idx++) {
const magnitude = 10 ** Math.floor(rng() * 4)
const sign_x = rng() > 0.5 ? 1 : -1
const sign_y = rng() > 0.5 ? 1 : -1
// some points near zero for the linear region
const near_zero = rng() < 0.2
const coord_x = near_zero ? (rng() - 0.5) * 20 : sign_x * magnitude * (0.5 + rng() * 0.5)
const coord_y = near_zero ? (rng() - 0.5) * 20 : sign_y * magnitude * (0.3 + rng() * 0.7)
values.x.push(coord_x)
values.y.push(coord_y)
values.color_values.push((coord_x * coord_y) / 1000) // x-y correlation creates a gradient
metadata.push({
idx,
quadrant: `${sign_x > 0 ? `+` : `-`}X, ${sign_y > 0 ? `+` : `-`}Y`,
magnitude: near_zero ? `near zero` : magnitude.toLocaleString(),
})
}
// neutral gray outline (visible on both light/dark bg) so the diverging scheme's
// near-white midpoint markers don't vanish against the background
const point_style = { radius: 6, stroke: `gray`, stroke_width: 1, fill_opacity: 0.85 }
const scale_of = (type: string) =>
type === `arcsinh` ? { type, threshold: arcsinh_threshold } : type
let [x_type, y_type, color_type] = $derived(dims.map((dim) => dim.type))
</script>
<div class="demo-controls">
{#each dims as dim (dim.key)}
<fieldset>
<legend>{dim.legend} Scale</legend>
{#each scale_types as scale (scale)}
<label>
<input type="radio" bind:group={dim.type} value={scale} />
{scale}
</label>
{/each}
</fieldset>
{/each}
{#if dims.some((dim) => dim.type === `arcsinh`)}
<label>
Arcsinh Threshold: {arcsinh_threshold}
<input
type="range"
bind:value={arcsinh_threshold}
min="0.1"
max="100"
step="0.1"
style="width: 200px"
/>
<span style="font-size: 0.85em; opacity: 0.7">
(smaller = sharper transition; default is 1, demo uses 10 for clearer visual
separation)
</span>
</label>
{/if}
</div>
{#each dims as { key, legend, type, effect } (key)}
{#if type === `log` && values[key].some((val) => val <= 0)}
<p class="warn">
⚠️ <strong>{legend} log scale invalid:</strong> Data contains negative/zero values. {effect}.
</p>
{/if}
{/each}
<p style="opacity: 0.8">
<strong>80 points</strong> spanning ±1000 with clusters at different magnitudes. Switch to
"log" to see points with negative values disappear.
</p>
<ScatterPlot
series={[{ ...values, point_style, metadata, markers: `points` }]}
x_axis={{ label: `X Axis (${x_type})`, scale_type: scale_of(x_type) }}
y_axis={{ label: `Y Axis (${y_type})`, scale_type: scale_of(y_type) }}
color_scale={{ type: scale_of(color_type), scheme: `interpolateRdBu` }}
color_bar={{ title: `X × Y / 1000` }}
style="height: 450px"
>
{#snippet tooltip({ x: coord_x, y: coord_y, color_value, metadata })}
<strong>Point #{metadata.idx + 1}</strong><br />
X: {coord_x.toFixed(1)}<br />
Y: {coord_y.toFixed(1)}<br />
Color: {color_value?.toFixed(2)}<br />
Quadrant: {metadata.quadrant}<br />
Magnitude: {metadata.magnitude}
{/snippet}
</ScatterPlot>Combined Interactive Scatter Plot with Custom Controls
Mixed display modes, markers, hover styling, and independent X/Y grid controls. Open the gear icon (top-right) for point size, line width, colors, and other style options:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
import { symbol_names } from 'matterviz/labels'
// Define categories and colors for data points
const categories = ['Group A', 'Group B', 'Group C']
const category_colors = ['crimson', 'royalblue', 'mediumseagreen']
// Create three data series with different styling
const series_data = categories.map((category, cat_idx) => {
const symbol = symbol_names[cat_idx % symbol_names.length]
const x = Array.from({ length: 10 }, (_, idx) => idx + 1)
return {
x,
y: x.map(() => 3 + cat_idx * 3 + Math.random() * 2),
point_style: {
fill: category_colors[cat_idx],
radius: 6 - cat_idx,
stroke: 'black',
stroke_width: 0.5,
symbol_type: symbol,
symbol_size: 40 + cat_idx * 5,
},
metadata: x.map((_, idx) => ({
category,
color: category_colors[cat_idx],
symbol,
idx,
})),
label: category,
}
})
let display_mode = $state('line+points')
// Toggle series visibility
let visible_series = $state(Object.fromEntries(categories.map((name) => [name, true])))
// Controls for random data points
let ticks = $state({ x: -5, y: -5 })
// Grid toggles
let display = $state({ x_grid: true, y_grid: true })
// Custom axis labels
let axis_labels = $state({ x: 'X Axis', y: 'Y Value' })
// Update series based on visibility toggles
let displayed_series = $derived(
series_data.filter((_, idx) => visible_series[categories[idx]]),
)
// Random points across positive and negative space, one series per category color
const random_coords = (count: number) =>
Array.from({ length: count }, () => Math.random() * 20 - 10)
const random_series = category_colors.map((fill, s_idx) => {
const sample_count = 20 + Math.floor(Math.random() * 20) // Varying number of points
return {
x: random_coords(sample_count),
y: random_coords(sample_count),
point_style: {
fill,
radius: 4 + s_idx, // Slightly different sizes
stroke: 'black',
stroke_width: 0.5,
symbol_type: symbol_names[(s_idx + 3) % symbol_names.length],
},
point_hover: {
scale: 1.5 + s_idx * 0.5, // Different hover scales
fill: 'orange',
stroke: 'white',
stroke_width: 2,
},
label: `Random Series ${s_idx + 1}`,
metadata: Array.from({ length: sample_count }, (_, p_idx) => ({
series: `Series ${s_idx + 1}`,
point: p_idx,
})),
}
})
</script>
<h3 id="interactive-multi-series-plot">Interactive Multi-Series Plot</h3>
<div class="demo-controls">
<label>
Display Mode:
<select bind:value={display_mode}>
<option value="points">Points only</option>
<option value="line">Lines only</option>
<option value="line+points">Lines and Points</option>
</select>
</label>
<!-- Legend with toggles -->
{#each categories as category, idx (category)}
<label>
<input type="checkbox" bind:checked={visible_series[category]} />
<span style:background={category_colors[idx]}></span>
{category}
</label>
{/each}
</div>
<ScatterPlot
series={displayed_series.map((srs) => ({ ...srs, markers: display_mode }))}
x_axis={{ label: axis_labels.x }}
y_axis={{ label: axis_labels.y }}
style="height: 400px;"
legend={null}
>
{#snippet tooltip({ x: coord_x, y: coord_y, metadata })}
<strong>{metadata.category}</strong><br />
Point {metadata.idx + 1} ({coord_x}, {coord_y.toFixed(2)})<br />
Symbol: {metadata.symbol}
{/snippet}
</ScatterPlot>
<h3 id="random-points-with-custom-controls-and-external-legend" style="margin-top: 2em">
Random Points with Custom Controls and External Legend
</h3>
<div class="demo-controls">
{#each Object.keys(ticks) as axis (axis)}
<label>
{axis} Tick Interval:
<select bind:value={ticks[axis]}>
{#each [2, 5, 10] as num (num)}
<option value={-num}>{num} units</option>
{/each}
</select>
</label>
{/each}
{#each ['x', 'y'] as axis (axis)}
<label>
<input type="checkbox" bind:checked={display[`${axis}_grid`]} />
{axis} Grid
</label>
{/each}
{#each Object.keys(axis_labels) as axis (axis)}
<label>
{axis} Label:
<input type="text" bind:value={axis_labels[axis]} style="width: 120px" />
</label>
{/each}
</div>
<ScatterPlot
series={random_series.map((srs) => ({ ...srs, markers: 'points' }))}
x_axis={{ label: axis_labels.x, range: [-15, 15], ticks: ticks.x }}
y_axis={{ label: axis_labels.y, range: [-15, 15], ticks: ticks.y }}
bind:display
class="external-legend-plot"
style="height: 400px; position: relative;"
legend={{
style: `
position: absolute;
top: 3pt;
left: var(--legend-left, 100%);
right: var(--legend-right, auto);
background: rgba(255, 255, 255, 0.1);
padding: 5px 5px 5px 0;
border-radius: 3px;
border: none;
`,
}}
>
{#snippet tooltip({ x: coord_x, y: coord_y, metadata })}
<strong>{metadata.series}</strong><br />
Position: ({coord_x.toFixed(2)}, {coord_y.toFixed(2)})<br />
Point Index: {metadata.point}
{/snippet}
</ScatterPlot>Automatic Color Bar Placement
The color bar picks the corner with the least data density (top-left, top-right, bottom-left, bottom-right). Move the quadrant sliders and watch it relocate. Point labels auto-place away from each other and their markers (auto_placement: true), and hide in crowds via label_placement_config={{ max_neighbors: { count, radius } }}.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// State for controlling point density in each quadrant
let density = $state({
top_left: 10,
top_right: 50,
bottom_left: 10,
bottom_right: 10,
})
// Lower-left corner of each quadrant in the 100 x 100 plot
const quadrants = {
bottom_left: [0, 0],
bottom_right: [50, 0],
top_left: [0, 50],
top_right: [50, 50],
}
// Reactive generation of plot data based on densities
let plot_series = $derived.by(() => {
const points = Object.entries(quadrants).flatMap(([quadrant, [x0, y0]]) =>
Array.from({ length: density[quadrant] }, () => ({
x: x0 + Math.random() * 50,
y: y0 + Math.random() * 50,
// quadrant center's distance from the origin, with some variation
color_value: Math.hypot(x0 + 25, y0 + 25) * Math.random() * 2,
})),
)
return [
{
x: points.map((point) => point.x),
y: points.map((point) => point.y),
color_values: points.map((point) => point.color_value),
point_label: points.map((point) => ({
text: point.color_value.toFixed(1),
auto_placement: true, // repel labels off each other and their markers
font_size: '12px',
})),
point_style: { radius: 5, stroke: 'white', stroke_width: 0.5 },
},
]
})
</script>
<div class="demo-controls">
{#each [['top_left', 'Top Left'], ['top_right', 'Top Right'], ['bottom_left', 'Bottom Left'], ['bottom_right', 'Bottom Right']] as [quadrant, label] (quadrant)}
<label
>{label}: {density[quadrant]}
<input
type="range"
min="0"
max="100"
value={density[quadrant]}
onchange={(evt) => (density[quadrant] = Number(evt.target.value))}
style="width: 100px"
/>
</label>
{/each}
</div>
<ScatterPlot
series={plot_series.map((srs) => ({ ...srs, markers: `points` }))}
x_axis={{ label: 'X Position', range: [0, 100], format: '~s' }}
y_axis={{ label: 'Y Position', range: [0, 100], format: '~s' }}
color_scale={{ scheme: `interpolateTurbo` }}
color_bar={{ title: `Color Bar Title` }}
label_placement_config={{ max_neighbors: { count: 2, radius: 35 } }}
style="height: 450px; margin-block: 1em"
>
{#snippet tooltip({ x_formatted, y_formatted, metadata, color_value })}
Point ({x_formatted}, {y_formatted})<br />
Color value: {color_value?.toFixed(2)}
{/snippet}
</ScatterPlot>Automatic Label Placement
When points cluster tightly, manual labels overlap. Set auto_placement: true on a point’s point_label to place labels with simulated annealing (SA):
- rectangular collision checks between labels
- penalty when a label covers a marker
- dotted leader lines from displaced labels back to their points
- label sizes from real font metrics
- labels constrained to the plot area
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Labelled points sharing one style, e.g. a dense cluster or isolated markers
const make_points = (coords, point_style, prefix, font_size) =>
coords.map(([x, y], idx) => ({
x,
y,
point_style,
text: `${prefix}${idx + 1}`,
font_size,
}))
const cluster = (center_x, center_y, count, radius) =>
Array.from({ length: count }, () => {
const [angle, dist] = [Math.random() * 2 * Math.PI, Math.random() * radius]
return [center_x + Math.cos(angle) * dist, center_y + Math.sin(angle) * dist]
})
const purple = { fill: 'rebeccapurple', radius: 8 }
const points = [
// Dense clusters (test collision avoidance)
...make_points(cluster(25, 75, 10, 6), purple, 'Dense-', '13px'),
...make_points(cluster(75, 25, 8, 5), purple, 'Packed-', '11px'),
// Isolated markers (test marker avoidance and boundary constraints)
...make_points(
[
[10, 10],
[90, 90],
[10, 90],
[90, 10],
[50, 50],
],
{ fill: 'darkorange', radius: 10 },
'Solo-',
'16px',
),
]
let auto_place_enabled = $state(true)
const series_data = $derived([
{
x: points.map((pt) => pt.x),
y: points.map((pt) => pt.y),
point_style: points.map((pt) => pt.point_style),
point_label: points.map(({ text, font_size }) => ({
text,
font_size,
auto_placement: auto_place_enabled,
})),
},
])
</script>
<label style="margin-bottom: 1em; display: block">
<input type="checkbox" bind:checked={auto_place_enabled} />
Enable Automatic Label Placement
</label>
<p style="font-size: 0.95em; opacity: 0.9">
Toggle to compare: with auto-placement ON, clustered labels (purple markers) separate to
avoid overlap, and isolated labels (orange markers) position below their markers. With it
OFF, you'll see overlaps.
</p>
<ScatterPlot
series={series_data.map((srs) => ({ ...srs, markers: 'points' }))}
x_axis={{ label: 'X Position', range: [0, 100] }}
y_axis={{ label: 'Y Position', range: [0, 100] }}
style="height: 500px"
/>Tuning Label Placement
The label placement algorithm exposes configuration via label_placement_config on ScatterPlot. You can tune the number of simulated annealing iterations (sa_iterations), the maximum label count before falling back to simple offsets (max_labels), the minimum displacement before a leader line is drawn (leader_line_threshold), and the energy function weights that control the tradeoff between overlap avoidance, anchor proximity, and boundary respect.
Adjust SA iterations and the leader-line threshold to see how placement changes:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Periodic table-inspired data: elements placed in a 2D grid with some clustering
const elements = [
{ x: 15, y: 85, text: 'H' },
{ x: 85, y: 85, text: 'He' },
{ x: 15, y: 70, text: 'Li' },
{ x: 25, y: 70, text: 'Be' },
{ x: 55, y: 70, text: 'B' },
{ x: 65, y: 70, text: 'C' },
{ x: 75, y: 70, text: 'N' },
{ x: 85, y: 70, text: 'O' },
{ x: 15, y: 55, text: 'Na' },
{ x: 25, y: 55, text: 'Mg' },
{ x: 55, y: 55, text: 'Al' },
{ x: 65, y: 55, text: 'Si' },
{ x: 75, y: 55, text: 'P' },
{ x: 85, y: 55, text: 'S' },
// Dense cluster of transition metals
{ x: 35, y: 40, text: 'Sc' },
{ x: 40, y: 40, text: 'Ti' },
{ x: 45, y: 40, text: 'V' },
{ x: 50, y: 40, text: 'Cr' },
{ x: 55, y: 40, text: 'Mn' },
{ x: 60, y: 40, text: 'Fe' },
{ x: 65, y: 40, text: 'Co' },
{ x: 70, y: 40, text: 'Ni' },
// Lanthanides packed tightly
{ x: 30, y: 18, text: 'La' },
{ x: 35, y: 18, text: 'Ce' },
{ x: 40, y: 18, text: 'Pr' },
{ x: 45, y: 18, text: 'Nd' },
{ x: 50, y: 18, text: 'Pm' },
{ x: 55, y: 18, text: 'Sm' },
{ x: 60, y: 18, text: 'Eu' },
{ x: 65, y: 18, text: 'Gd' },
]
let sa_iterations = $state(1000)
let leader_threshold = $state(15)
const series = $derived([
{
x: elements.map((element) => element.x),
y: elements.map((element) => element.y),
point_style: elements.map((element) => ({
fill: element.y > 60 ? '#3b82f6' : element.y > 30 ? '#f59e0b' : '#ef4444',
radius: 5,
stroke: 'white',
stroke_width: 1,
})),
point_label: elements.map((element) => ({
text: element.text,
auto_placement: true,
font_size: '11px',
})),
},
])
</script>
<div class="demo-controls">
<label>
SA iterations: <strong>{sa_iterations}</strong>
<input type="range" min="100" max="5000" step="100" bind:value={sa_iterations} />
</label>
<label>
Leader line threshold: <strong>{leader_threshold}px</strong>
<input type="range" min="0" max="50" step="1" bind:value={leader_threshold} />
</label>
</div>
{#key `${sa_iterations}-${leader_threshold}`}
<ScatterPlot
series={series.map((srs) => ({ ...srs, markers: 'points' }))}
x_axis={{ label: 'Group', range: [5, 95] }}
y_axis={{ label: 'Period', range: [5, 95] }}
label_placement_config={{ sa_iterations, leader_line_threshold: leader_threshold }}
style="height: 500px"
/>
{/key}External Vertical Color Bar with Dynamic Controls
Vertical color bar on the right, outside the plot, spanning the full height. Change the color scheme and switch between linear and log color scales below.
Interactive example
svelte<script lang="ts">
import { ColorScaleSelect, ScatterPlot } from 'matterviz'
// 50 points from 5 to 95 on both axes, colored by index (1..99)
const idx_range = Array.from({ length: 50 }, (_, idx) => idx)
const vertical_color_data = {
x: idx_range.map((idx) => (idx / 50) * 90 + 5),
y: idx_range.map(() => Math.random() * 90 + 5),
color_values: idx_range.map((idx) => idx * 2 + 1),
point_style: { radius: 6, stroke: `black`, stroke_width: 0.5 },
metadata: idx_range.map((idx) => ({ value: idx * 2 })),
}
// Right padding makes space for the external color bar; the other sides fit the axes,
// so the bar's height follows the padding the plot resolves
const plot_padding = { r: 70 }
let resolved_padding = $state({ t: 20, b: 50, l: 50, r: 70 })
// Color Scaling Controls
let color_scale = $state({ type: `linear`, scheme: `interpolateCool` }) // Track which color scale type is active
</script>
<div class="demo-controls">
<strong>Color Scale Type:</strong>
{#each [`linear`, `log`] as scale_type (scale_type)}
<label>
<input type="radio" name="scale_type" value={scale_type} bind:group={color_scale.type} />
{scale_type}
</label>
{/each}
<ColorScaleSelect bind:value={color_scale.scheme} style="min-width: 250px" />
</div>
<ScatterPlot
series={[{ ...vertical_color_data, markers: 'points' }]}
x_axis={{ label: 'X Position', range: [0, 100], format: '~s' }}
y_axis={{ label: 'Y Position', range: [0, 100], format: '~s' }}
{color_scale}
padding={plot_padding}
bind:resolved_padding
color_bar={{
title: `Color Bar Title (${color_scale.type})`,
orientation: `vertical`,
tick_side: `primary`,
wrapper_style: `
position: absolute;
right: 10px;
inset-block: 0;
margin-block: auto;
height: calc(100% - ${resolved_padding.t + resolved_padding.b}px);
max-height: 100%;
`,
bar_style: `width: 15px; height: 100%;`,
}}
style="height: 400px"
>
{#snippet tooltip({ x_formatted, y_formatted, metadata, color_value })}
Point ({x_formatted}, {y_formatted})<br />
Color value: {color_value?.toFixed(1)}
{/snippet}
</ScatterPlot>Line Clipping with Fixed Ranges
Lines that leave the fixed x_axis.range / y_axis.range are clipped at the plot edges on all four sides (clipPath).
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Function to generate a line that extends beyond the limits
const generate_line = (start_x, start_y, end_x, end_y, steps, label) => {
const line = { x: [], y: [], label }
for (let idx = 0; idx <= steps; idx++) {
const fraction = idx / steps
line.x.push(start_x + (end_x - start_x) * fraction)
line.y.push(start_y + (end_y - start_y) * fraction)
}
return line
}
// Function to generate a curved line (parabola)
const generate_parabola = (start_x, end_x, curvature, vertical_shift, steps, label) => {
const curve = { x: [], y: [], label }
for (let idx = 0; idx <= steps; idx++) {
const coord_x = start_x + (end_x - start_x) * (idx / steps)
// Simple downward-opening parabola: y = -curvature * x^2 + shift
curve.x.push(coord_x)
curve.y.push(-curvature * coord_x * coord_x + vertical_shift)
}
return curve
}
// Function to generate a curved line (sine wave)
const generate_sine_wave = (
start_x,
end_x,
amplitude,
frequency,
vertical_shift,
steps,
label,
) => {
const wave = { x: [], y: [], label }
for (let idx = 0; idx <= steps; idx++) {
const coord_x = start_x + (end_x - start_x) * (idx / steps)
wave.x.push(coord_x)
wave.y.push(amplitude * Math.sin(frequency * coord_x) + vertical_shift)
}
return wave
}
// Create lines that cross all boundaries
const clipping_series = [
// Line crossing left and right boundaries
generate_line(-10, 0, 10, 0, 20, 'Left-Right'),
// Line crossing top and bottom boundaries
generate_line(0, -10, 0, 10, 20, 'Top-Bottom'),
// Diagonal line crossing top-left and bottom-right
generate_line(-10, 10, 10, -10, 20, 'TopLeft-BottomRight'),
// Diagonal line crossing bottom-left and top-right
generate_line(-10, -10, 10, 10, 20, 'BottomLeft-TopRight'),
// Line completely outside (should not be visible)
generate_line(15, 15, 20, 20, 5, 'Outside'),
// Line starting inside, ending outside (top-right)
generate_line(2, 2, 15, 15, 10, 'Inside-TopRight'),
// Line starting outside (bottom-left), ending inside
generate_line(-15, -15, -2, -2, 10, 'BottomLeft-Inside'),
// Parabola opening downwards, exiting bottom
generate_parabola(-10, 10, 0.2, 0, 40, 'Parabola (Bottom Exit)'),
// Sine wave mostly below the bottom edge
generate_sine_wave(-10, 10, 4, 1, -6, 50, 'Sine Wave (Below Bottom)'),
// Parabola starting inside, exiting bottom-right
generate_parabola(-2, 10, 0.15, 4, 30, 'Parabola (Inside-BottomRight Exit)'),
]
// Add some basic styling
clipping_series.forEach((series_data, idx) => {
series_data.line_style = {
color: `hsl(${idx * 60}, 70%, 50%)`,
width: 2,
}
})
</script>
<ScatterPlot
series={clipping_series.map((srs) => ({ ...srs, markers: 'line' }))}
x_axis={{ range: [-5, 5], label: 'X Axis (Fixed Range)' }}
y_axis={{ range: [-5, 5], label: 'Y Axis (Fixed Range)' }}
style="height: 400px"
/>Legend Grouping
Group legend items with legend_group (e.g. DFT methods, ML potentials, experiment). Click the group header to toggle all series in the group, or the chevron (▶) to collapse/expand.
Series with identical labels remain independent. To combine several drawing series into one legend entry that toggles together, give them the same legend_id and unique id values. legend_group creates a collapsible section; legend_id identifies a shared entry within it.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Grouped series data - comparing DFT methods vs ML potentials vs experiment
const grouped_series = [
// DFT group
{
x: [1, 2, 3, 4, 5],
y: [2.1, 4.2, 3.1, 5.3, 4.0],
label: 'PBE',
legend_group: 'DFT',
point_style: { fill: '#3498db', radius: 5 },
line_style: { color: '#3498db', width: 2 },
markers: 'line+points',
},
{
x: [1, 2, 3, 4, 5],
y: [2.3, 4.5, 3.4, 5.6, 4.2],
label: 'LDA',
legend_group: 'DFT',
point_style: { fill: '#2980b9', radius: 5 },
line_style: { color: '#2980b9', width: 2, dash: '5 3' },
markers: 'line+points',
},
// ML Potentials group
{
x: [1, 2, 3, 4, 5],
y: [2.0, 4.0, 3.0, 5.1, 3.9],
label: 'MACE',
legend_group: 'ML Potentials',
point_style: { fill: '#e74c3c', radius: 5 },
line_style: { color: '#e74c3c', width: 2 },
markers: 'line+points',
},
{
x: [1, 2, 3, 4, 5],
y: [2.2, 4.3, 3.2, 5.4, 4.1],
label: 'CHGNet',
legend_group: 'ML Potentials',
point_style: { fill: '#c0392b', radius: 5 },
line_style: { color: '#c0392b', width: 2, dash: '5 3' },
markers: 'line+points',
},
{
x: [1, 2, 3, 4, 5],
y: [1.9, 3.8, 2.9, 4.9, 3.7],
label: 'M3GNet',
legend_group: 'ML Potentials',
point_style: { fill: '#a93226', radius: 5 },
line_style: { color: '#a93226', width: 2, dash: '2 2' },
markers: 'line+points',
},
// Experiment (ungrouped)
{
x: [1, 2, 3, 4, 5],
y: [2.0, 4.1, 3.0, 5.2, 4.0],
label: 'Experiment',
point_style: { fill: '#2ecc71', radius: 7, symbol_type: 'Star' },
markers: 'points',
},
]
</script>
<ScatterPlot
series={grouped_series}
x_axis={{ label: 'Sample Index' }}
y_axis={{ label: 'Energy (eV)' }}
legend={{ draggable: true }}
style="height: 400px"
>
{#snippet tooltip({ x: coord_x, y: coord_y, label })}
<strong>{label}</strong><br />
Sample {coord_x}: {coord_y.toFixed(2)} eV
{/snippet}
</ScatterPlot>Multiple Plots in 2×2 Grid Layout
Display multiple scatter plots in a responsive 2×2 grid:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
const make_data = (callback) => {
const x_vals = Array.from({ length: 30 }, (_, idx) => idx)
return { x: x_vals, y: x_vals.map(callback) }
}
const plots = [
{ title: 'Linear', data: make_data((coord_x) => 2 * coord_x + Math.random() * 10) },
{
title: 'Quadratic',
data: make_data((coord_x) => (coord_x - 15) ** 2 / 10 + Math.random() * 5),
},
{
title: 'Exponential',
data: make_data((coord_x) => Math.exp(coord_x / 10) + Math.random() * 2),
},
{
title: 'Sine',
data: make_data((coord_x) => 15 + 10 * Math.sin(coord_x / 3) + Math.random() * 2),
},
]
</script>
<div class="grid bleed-1400">
{#each plots as { title, data } (title)}
<div class="cell">
<h4>{title}</h4>
<ScatterPlot
series={[data]}
x_axis={{ label: 'x', range: [0, null] }}
y_axis={{ label: 'y' }}
/>
</div>
{/each}
</div>Fill Between Series and Error Bands
fill_regions fills areas between boundaries given as series, constants, functions, or raw arrays. error_bands is a shorthand for uncertainty ranges around a series. Both support hover and show in the legend.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Generate two series to fill between
const x_values = Array.from({ length: 20 }, (_, idx) => idx)
const upper_series = {
x: x_values,
y: x_values.map((val) => 10 + 3 * Math.sin(val * 0.5) + Math.random()),
label: 'Upper Bound',
point_style: { fill: '#e74c3c', radius: 4 },
line_style: { color: '#e74c3c', width: 2 },
markers: 'line+points',
}
const lower_series = {
x: x_values,
y: x_values.map((val) => 5 + 2 * Math.sin(val * 0.5) + Math.random()),
label: 'Lower Bound',
point_style: { fill: '#3498db', radius: 4 },
line_style: { color: '#3498db', width: 2 },
markers: 'line+points',
}
// Series with error bands
const data_with_errors = {
x: x_values,
y: x_values.map((val) => 15 + 2 * Math.cos(val * 0.3)),
label: 'Measurement',
point_style: { fill: '#2ecc71', radius: 5 },
line_style: { color: '#2ecc71', width: 2 },
markers: 'line+points',
}
// Asymmetric errors (larger above than below)
const upper_errors = x_values.map(() => 1 + Math.random() * 1.5)
const lower_errors = x_values.map(() => 0.5 + Math.random() * 0.5)
// Fill between the two series
const fill_regions = [
{
upper: { type: 'series', series_idx: 0 },
lower: { type: 'series', series_idx: 1 },
fill: 'rgba(155, 89, 182, 0.3)',
label: 'Range Between',
edge_upper: { color: '#9b59b6', width: 1 },
},
]
// Error band with asymmetric errors
const error_bands = [
{
series: { type: 'series', series_idx: 2 },
error: { upper: upper_errors, lower: lower_errors },
fill: '#2ecc71',
fill_opacity: 0.25,
label: '±Error',
},
]
let hovered_fill = $state(null)
</script>
<ScatterPlot
series={[upper_series, lower_series, data_with_errors]}
{fill_regions}
{error_bands}
on_fill_hover={(event) => (hovered_fill = event)}
x_axis={{ label: 'X Value' }}
y_axis={{ label: 'Y Value', range: [0, 20] }}
style="height: 400px"
/>
<div style="margin-top: 0.5em; font-size: 0.9em">
{#if hovered_fill}
Hovering: {hovered_fill.label ?? `Fill region ${hovered_fill.region_idx + 1}`}
{:else}
Hover over filled areas to see interaction
{/if}
</div>Fill regions and error bands accept a pattern (a shape name, plotly-style shorthand like / or x, or a PatternOptions object) to hatch the area so overlapping bands stay legible where they intersect and in grayscale print. The texture is tiled in screen space, so it stays crisp under zoom, and the legend swatch repeats it:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
const x_values = Array.from({ length: 40 }, (_, idx) => idx / 4)
const model_a = {
x: x_values,
y: x_values.map((val) => 4 + 2 * Math.sin(val)),
label: `Model A`,
line_style: { color: `#4c6ef5`, width: 2 },
markers: `line`,
}
const model_b = {
x: x_values,
y: x_values.map((val) => 4.5 + 1.5 * Math.cos(val * 0.8)),
label: `Model B`,
line_style: { color: `#e8590c`, width: 2 },
markers: `line`,
}
const error_bands = [
{
series: { type: `series`, series_idx: 0 },
error: 0.8,
fill: `#4c6ef5`,
fill_opacity: 0.35,
label: `A ± σ`,
pattern: { shape: `diagonal`, size: 7 },
},
{
series: { type: `series`, series_idx: 1 },
error: 0.6,
fill: `#e8590c`,
fill_opacity: 0.35,
label: `B ± σ`,
pattern: { shape: `diagonal-reverse`, size: 7 },
},
]
const fill_regions = [
{
upper: { type: `constant`, value: 1.5 },
lower: { type: `constant`, value: 0 },
fill: `#868e96`,
fill_opacity: 0.3,
label: `Excluded`,
pattern: { shape: `cross-diagonal`, mode: `replace`, size: 10 },
},
]
</script>
<ScatterPlot
series={[model_a, model_b]}
{error_bands}
{fill_regions}
x_axis={{ label: `Time (ps)` }}
y_axis={{ label: `Energy (eV)`, range: [0, 8] }}
style="height: 400px"
/>Conditional Fills and Function Boundaries
Use the where condition to fill only where a condition is true, e.g. highlighting regions where one series exceeds another. Boundaries can also be defined as functions for dynamic fills like confidence intervals or thresholds.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Two crossing series
const x_values = Array.from({ length: 30 }, (_, idx) => idx * 0.5)
const series_a = {
x: x_values,
y: x_values.map((val) => 8 + 4 * Math.sin(val)),
label: 'Series A',
point_style: { fill: '#e74c3c', radius: 3 },
line_style: { color: '#e74c3c', width: 2 },
markers: 'line+points',
}
const series_b = {
x: x_values,
y: x_values.map((val) => 8 + 3 * Math.cos(val * 0.8)),
label: 'Series B',
point_style: { fill: '#3498db', radius: 3 },
line_style: { color: '#3498db', width: 2 },
markers: 'line+points',
}
// Fill only where A > B (green) and where B > A (orange)
const fill_regions = [
{
upper: { type: 'series', series_idx: 0 },
lower: { type: 'series', series_idx: 1 },
where: (_unused_coord_x, y_upper, y_lower) => y_upper > y_lower,
fill: 'rgba(46, 204, 113, 0.4)',
label: 'A > B',
curve: 'monotoneX',
},
{
upper: { type: 'series', series_idx: 1 },
lower: { type: 'series', series_idx: 0 },
where: (_unused_coord_x, y_upper, y_lower) => y_upper > y_lower,
fill: 'rgba(230, 126, 34, 0.4)',
label: 'B > A',
curve: 'monotoneX',
},
// Function boundary: fill below a threshold line
{
upper: { type: 'function', fn: () => 4 },
lower: 0,
fill: 'rgba(52, 152, 219, 0.15)',
label: 'Below Threshold',
z_index: 'below-grid',
},
]
let clicked_region = $state(null)
</script>
<ScatterPlot
series={[series_a, series_b]}
{fill_regions}
on_fill_click={(event) => (clicked_region = event)}
x_axis={{ label: 'X Value' }}
y_axis={{ label: 'Y Value', range: [0, 14] }}
style="height: 400px"
/>
<div style="margin-top: 0.5em; font-size: 0.9em">
{#if clicked_region}
Clicked: <strong>{clicked_region.label}</strong> at x={clicked_region.px.toFixed(0)}px
{:else}
Click on a filled region to see the event
{/if}
</div>Fill Between Series with Mismatched X-Values
Series on different x-grids need no resampling: each boundary keeps its own points and is drawn with the region’s curve.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Series A: sparse sampling (every 2 units)
const sparse_x = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
const series_sparse = {
x: sparse_x,
y: sparse_x.map((val) => 8 + 3 * Math.sin(val * 0.4)),
label: 'Sparse (11 pts)',
point_style: { fill: '#e74c3c', radius: 6 },
line_style: { color: '#e74c3c', width: 2 },
markers: 'line+points',
}
// Series B: dense sampling (every 0.5 units) with offset x-values
const dense_x = Array.from({ length: 41 }, (_, idx) => idx * 0.5)
const series_dense = {
x: dense_x,
y: dense_x.map((val) => 5 + 2 * Math.cos(val * 0.6)),
label: 'Dense (41 pts)',
point_style: { fill: '#3498db', radius: 3 },
line_style: { color: '#3498db', width: 2 },
markers: 'line+points',
}
// Fill between mismatched series - interpolation happens automatically
const fill_regions = [
{
upper: { type: 'series', series_idx: 0 },
lower: { type: 'series', series_idx: 1 },
fill: 'rgba(155, 89, 182, 0.35)',
label: 'Interpolated Fill',
curve: 'monotoneX',
},
]
</script>
<ScatterPlot
series={[series_sparse, series_dense]}
{fill_regions}
x_axis={{ label: 'X Value', range: [0, 20] }}
y_axis={{ label: 'Y Value', range: [0, 14] }}
style="height: 350px"
/>Fills Between Partially Overlapping Series
Fills are drawn only where both boundaries’ x-ranges overlap; non-overlapping parts get no fill. A constant boundary follows its companion’s x positions, so it spans the companion’s full range.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Series 1: x from 0 to 8
const series_left = {
x: [0, 2, 4, 6, 8],
y: [3, 5, 7, 6, 4],
label: 'Left (0-8)',
point_style: { fill: '#e74c3c', radius: 5 },
line_style: { color: '#e74c3c', width: 2 },
markers: 'line+points',
}
// Series 2: x from 6 to 14 (partial overlap with series 1)
const series_right = {
x: [6, 8, 10, 12, 14],
y: [2, 3, 5, 4, 3],
label: 'Right (6-14)',
point_style: { fill: '#3498db', radius: 5 },
line_style: { color: '#3498db', width: 2 },
markers: 'line+points',
}
// Series 3: x from 16 to 20 (no overlap)
const series_far = {
x: [16, 17, 18, 19, 20],
y: [6, 8, 7, 9, 8],
label: 'Far Right (16-20)',
point_style: { fill: '#2ecc71', radius: 5 },
line_style: { color: '#2ecc71', width: 2 },
markers: 'line+points',
}
// Multiple fills showing different overlap scenarios
const fill_regions = [
{
upper: { type: 'series', series_idx: 0 },
lower: { type: 'series', series_idx: 1 },
fill: 'rgba(155, 89, 182, 0.3)',
label: 'Partial Overlap',
curve: 'linear',
},
{
upper: { type: 'series', series_idx: 2 },
lower: 2, // Constant boundary
fill: 'rgba(46, 204, 113, 0.3)',
label: 'Constant Boundary',
curve: 'linear',
},
]
</script>
<ScatterPlot
series={[series_left, series_right, series_far]}
{fill_regions}
x_axis={{ label: 'X Value', range: [0, 22] }}
y_axis={{ label: 'Y Value', range: [0, 12] }}
style="height: 350px"
/>Fill with Different Curve Types
curve controls how the fill area interpolates between points. Side-by-side comparison of curve types:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Same data for all plots
const x_values = [0, 2, 4, 6, 8, 10, 12, 14]
const upper_y = [8, 10, 7, 11, 9, 12, 8, 10]
const lower_y = [3, 5, 2, 4, 3, 5, 2, 4]
const make_series = () => [
{
x: x_values,
y: upper_y,
label: 'Upper',
point_style: { fill: '#e74c3c', radius: 4 },
line_style: { color: '#e74c3c', width: 2 },
markers: 'line+points',
},
{
x: x_values,
y: lower_y,
label: 'Lower',
point_style: { fill: '#3498db', radius: 4 },
line_style: { color: '#3498db', width: 2 },
markers: 'line+points',
},
]
const curve_types = ['linear', 'monotoneX', 'step', 'basis']
const colors = [
'rgba(155, 89, 182, 0.4)',
'rgba(46, 204, 113, 0.4)',
'rgba(230, 126, 34, 0.4)',
'rgba(52, 152, 219, 0.4)',
]
</script>
<section>
{#each curve_types as curve_type, idx (curve_type)}
<div>
<strong style="text-transform: capitalize">{curve_type}</strong>
<ScatterPlot
series={make_series()}
fill_regions={[
{
upper: { type: 'series', series_idx: 0 },
lower: { type: 'series', series_idx: 1 },
fill: colors[idx],
label: `${curve_type} Fill`,
curve: curve_type,
},
]}
x_axis={{ label: 'X', range: [0, 15] }}
y_axis={{ label: 'Y', range: [0, 14] }}
style="height: 250px"
legend={null}
/>
</div>
{/each}
</section>Reference Lines: Horizontal, Vertical, and Diagonal
ref_lines adds horizontal, vertical, and diagonal reference lines (thresholds, targets, parity, annotations), with custom style, annotations, z-index, hover, and click handlers.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Sample data points
const data = {
x: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
y: [2.1, 3.8, 5.2, 4.5, 6.8, 7.2, 8.5, 9.1, 8.8, 10.2],
point_style: { fill: `steelblue`, radius: 6 },
markers: `points`,
label: `Measurements`,
}
// Reference lines with different types
let ref_lines = $state([
// Horizontal line - target value
{
type: `horizontal`,
y: 7,
label: `Target`,
style: { color: `#e74c3c`, width: 2, dash: `8 4` },
annotation: { text: `Target = 7`, position: `end`, side: `above` },
},
// Vertical line - threshold
{
type: `vertical`,
x: 5.5,
label: `Phase Boundary`,
style: { color: `#2ecc71`, width: 2 },
annotation: { text: `Phase I → II`, position: `center`, side: `right` },
},
// Diagonal line - parity/identity line
{
type: `diagonal`,
slope: 1,
intercept: 0,
label: `y = x`,
style: { color: `#9b59b6`, width: 1.5, dash: `4 2` },
annotation: { text: `Parity`, position: `end`, side: `below` },
},
// Another diagonal - trend line
{
type: `diagonal`,
slope: 0.8,
intercept: 1.5,
label: `Trend`,
style: { color: `#f39c12`, width: 2 },
annotation: { text: `Trend: y = 0.8x + 1.5`, position: `start`, side: `above` },
z_index: `below-grid`,
},
])
</script>
<ScatterPlot
series={[data]}
{ref_lines}
x_axis={{ label: `X Value`, range: [0, 12] }}
y_axis={{ label: `Y Value`, range: [0, 12] }}
style="height: 400px"
/>
<div class="demo-controls" style="font-size: 0.9em">
{#each ref_lines as line (line.label)}
<label>
<input
type="checkbox"
checked={line.visible !== false}
onchange={() => {
line.visible = line.visible === false
ref_lines = [...ref_lines]
}}
/>
{line.label}
</label>
{/each}
</div>Reference Line Segments and Through-Points
Create line segments between specific points, or lines that extend through two points to the plot edges:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Data with clusters
const cluster_a = {
x: [2, 2.5, 3, 2.8, 2.2],
y: [8, 8.5, 7.8, 9, 8.2],
point_style: { fill: `#e74c3c`, radius: 6 },
label: `Cluster A`,
markers: `points`,
}
const cluster_b = {
x: [7, 7.5, 8, 7.2, 8.2],
y: [3, 2.5, 3.5, 2.8, 3.2],
point_style: { fill: `#3498db`, radius: 6 },
label: `Cluster B`,
markers: `points`,
}
// Reference lines connecting clusters and showing decision boundaries
const ref_lines = [
// Segment connecting cluster centers
{
type: `segment`,
p1: [2.5, 8.3],
p2: [7.5, 3],
label: `Cluster Link`,
style: { color: `#2ecc71`, width: 2 },
annotation: { text: `d = 6.7`, position: `center`, side: `above` },
},
// Decision boundary (perpendicular bisector, extends to edges)
{
type: `line`,
p1: [3, 4],
p2: [7, 7],
label: `Decision Boundary`,
style: { color: `#9b59b6`, width: 2, dash: `6 3` },
annotation: { text: `Boundary`, position: `end`, side: `above` },
},
// Horizontal mean line for cluster A
{
type: `horizontal`,
y: 8.3,
x_span: [1.5, 3.5],
label: `A mean`,
style: { color: `#e74c3c`, width: 1, dash: `4 2`, opacity: 0.7 },
},
// Horizontal mean line for cluster B
{
type: `horizontal`,
y: 3,
x_span: [6.5, 8.5],
label: `B mean`,
style: { color: `#3498db`, width: 1, dash: `4 2`, opacity: 0.7 },
},
]
</script>
<ScatterPlot
series={[cluster_a, cluster_b]}
{ref_lines}
x_axis={{ label: `Feature 1`, range: [0, 10] }}
y_axis={{ label: `Feature 2`, range: [0, 10] }}
style="height: 400px"
/>Interactive Reference Lines with Hover and Click
Reference lines support interactive features including hover styling, click handlers, and custom metadata:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
const data = {
x: Array.from({ length: 20 }, () => Math.random() * 10),
y: Array.from({ length: 20 }, () => Math.random() * 10),
point_style: { fill: `steelblue`, radius: 5 },
markers: `points`,
}
let clicked_info = $state(`Click on a reference line`)
let hovered_info = $state(`Hover over a line`)
const show_click = (event) => {
const metadata = JSON.stringify(event.metadata)
clicked_info = `Clicked: ${event.label} (id: ${event.line_id}), metadata: ${metadata}`
}
const on_hover = (event) => {
hovered_info = event ? `Hovering: ${event.label}` : `Hover over a line`
}
const ref_lines = [
{
type: `horizontal`,
y: 3,
id: `lower_threshold`,
label: `Lower Threshold`,
style: { color: `#e74c3c`, width: 2 },
hover_style: { color: `#c0392b`, width: 4 },
annotation: { text: `Min = 3`, position: `start`, side: `below` },
metadata: { description: `Minimum acceptable value`, severity: `warning` },
on_click: show_click,
on_hover,
},
{
type: `horizontal`,
y: 7,
id: `upper_threshold`,
label: `Upper Threshold`,
style: { color: `#2ecc71`, width: 2 },
hover_style: { color: `#27ae60`, width: 4 },
annotation: { text: `Max = 7`, position: `start`, side: `above` },
metadata: { description: `Maximum acceptable value`, severity: `info` },
on_click: show_click,
on_hover,
},
{
type: `vertical`,
x: 5,
id: `midpoint`,
label: `Midpoint`,
style: { color: `#f39c12`, width: 2, dash: `5 5` },
hover_style: { color: `#d35400`, width: 3 },
annotation: { text: `x = 5`, position: `end`, side: `right` },
on_click: (event) => {
clicked_info = `Clicked: ${event.label} at x=${event.type === 'vertical' ? 5 : 'N/A'}`
},
on_hover,
},
]
</script>
<ScatterPlot
series={[data]}
{ref_lines}
x_axis={{ label: `X`, range: [0, 10] }}
y_axis={{ label: `Y`, range: [0, 10] }}
style="height: 400px"
/>
<aside>
<div><strong>Clicked:</strong> {clicked_info}</div>
<div><strong>Hovered:</strong> {hovered_info}</div>
</aside>Reference Lines with Z-Index Layering
Control where reference lines appear in the rendering stack using z_index. Options are below-grid, below-lines (default), below-points, and above-all. Toggle the layer below and watch the reference band move up the stack, progressively covering the grid, then the connecting line, then the on-band points (which switch from crisp on top to dimmed underneath):
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Data zig-zags across y=5.5 so odd-x points sit ON the reference band while the connecting
// line repeatedly crosses it, maximizing overlap so the chosen layer is visually obvious
const series = [
{
x: [1, 2, 3, 4, 5, 6, 7, 8, 9],
y: [5.5, 8.5, 5.5, 2.5, 5.5, 8.5, 5.5, 2.5, 5.5],
point_style: { fill: `#3498db`, radius: 11 },
line_style: { color: `#3498db`, width: 4 },
markers: `line+points`,
label: `Data Series`,
},
]
let z_index = $state(`below-points`)
const ref_line_config = $derived({
type: `horizontal`,
y: 5.5,
// semi-transparent band: dims whatever sits below it, stays crisp above whatever it covers
style: { color: `rgba(231, 76, 60, 0.55)`, width: 20 },
z_index,
annotation: {
text: `z_index: ${z_index}`,
position: `end`,
side: `above`,
gap: 18, // clear the 20px-thick band so the label stays readable above it
},
})
</script>
<div class="demo-controls">
<strong>Z-Index:</strong>
{#each [`below-grid`, `below-lines`, `below-points`, `above-all`] as z_index_2 (z_index_2)}
<label>
<input type="radio" bind:group={z_index} value={z_index_2} />
{z_index_2}
</label>
{/each}
</div>
<ScatterPlot
{series}
ref_lines={[ref_line_config]}
x_axis={{ label: `X`, range: [0, 10], grid_style: { 'stroke-width': 2 } }}
y_axis={{ label: `Y`, range: [0, 10], grid_style: { 'stroke-width': 2 } }}
style="height: 350px"
/>Reference Lines with Time Axes
Reference lines work with time-based x-axes. Use Date objects or ISO strings for time values:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Generate time series data for the past 30 days
const now = Date.now()
const day_ms = 24 * 60 * 60 * 1000
const dates = Array.from({ length: 30 }, (_, idx) => now - (30 - idx) * day_ms)
const values = dates.map((_, idx) => 50 + 20 * Math.sin(idx * 0.3) + Math.random() * 10)
const series = [
{
x: dates,
y: values,
point_style: { fill: `steelblue`, radius: 4 },
line_style: { color: `steelblue`, width: 2 },
markers: `line+points`,
label: `Daily Metric`,
},
]
// Reference lines using Date objects
const ref_lines = [
{
type: `vertical`,
x: now - 15 * day_ms,
style: { color: `#e74c3c`, width: 2 },
annotation: { text: `Release Date`, position: `end`, side: `right` },
},
{
type: `vertical`,
x: now - 7 * day_ms,
style: { color: `#2ecc71`, width: 2, dash: `4 2` },
annotation: { text: `Week Ago`, position: `end`, side: `left` },
},
{
type: `horizontal`,
y: 65,
style: { color: `#f39c12`, width: 2, dash: `6 3` },
annotation: { text: `Target`, position: `end`, side: `above` },
},
{
type: `horizontal`,
y: 35,
style: { color: `#9b59b6`, width: 1.5, dash: `4 4` },
annotation: { text: `Minimum`, position: `end`, side: `below` },
},
]
</script>
<ScatterPlot
{series}
{ref_lines}
x_axis={{ label: `Date`, scale_type: `time`, format: `%b %d` }}
y_axis={{ label: `Value`, range: [20, 80] }}
style="height: 400px"
/>Interactive Axis Labels with Lazy Data Loading
- 240 data points (80 per material class) to test rendering performance
- 6 switchable properties on each axis with realistic correlations
- Multi-series support with 3 material classes (Metals, Ceramics, Polymers)
- Variable loading delays (200-800ms) simulating real API latency
- Error simulation (5% chance) to test error handling
Interactive example
svelte<script lang="ts">
import { onDestroy } from 'svelte'
import { ScatterPlot, create_axis_loader, type AxisKey } from 'matterviz'
import { seeded_rng } from '#site/histogram-data.js'
type MaterialData = {
density: number
bandgap: number
conductivity: number
formation_energy: number
bulk_modulus: number
thermal_expansion: number
}
// Generate realistic materials data with correlations
function generate_property_data(n_points: number, base_seed: number) {
const rng = seeded_rng(base_seed)
const data: Record<string, MaterialData[]> = { metals: [], ceramics: [], polymers: [] }
for (let idx = 0; idx < n_points; idx++) {
// Metals: high density, low bandgap, high conductivity
data.metals.push({
density: 5 + rng() * 15 + Math.sin(idx * 0.1) * 2,
bandgap: rng() * 0.5,
conductivity: 1e5 + rng() * 1e7,
formation_energy: -3 - rng() * 2 + Math.cos(idx * 0.05),
bulk_modulus: 50 + rng() * 200,
thermal_expansion: 5 + rng() * 20,
})
// Ceramics: medium density, wide bandgap, low conductivity
data.ceramics.push({
density: 2 + rng() * 6,
bandgap: 2 + rng() * 8,
conductivity: 1e-10 + rng() * 1e-5,
formation_energy: -5 - rng() * 3 - Math.sin(idx * 0.08),
bulk_modulus: 100 + rng() * 300,
thermal_expansion: 2 + rng() * 10,
})
// Polymers: low density, variable bandgap, insulating
data.polymers.push({
density: 0.8 + rng() * 1.5,
bandgap: 3 + rng() * 6,
conductivity: 1e-18 + rng() * 1e-12,
formation_energy: -1 - rng() * 2,
bulk_modulus: 1 + rng() * 10,
thermal_expansion: 50 + rng() * 200,
})
}
return data
}
const n_points = 80
const all_data = generate_property_data(n_points, 42)
// Property definitions with HTML sub/superscripts
const properties = {
density: { label: `Density ρ`, unit: `g·cm<sup>−3</sup>`, scale: `linear` },
bandgap: { label: `Band Gap E<sub>gap</sub>`, unit: `eV`, scale: `linear` },
conductivity: { label: `Conductivity σ`, unit: `S·m<sup>−1</sup>`, scale: `log` },
formation_energy: {
label: `Formation Energy E<sub>form</sub>`,
unit: `eV/atom`,
scale: `linear`,
},
bulk_modulus: { label: `Bulk Modulus K`, unit: `GPa`, scale: `linear` },
thermal_expansion: {
label: `Thermal Expansion α<sub>th</sub>`,
unit: `10<sup>−6</sup> K<sup>−1</sup>`,
scale: `linear`,
},
}
// Series colors
const colors = { metals: `#e74c3c`, ceramics: `#3498db`, polymers: `#2ecc71` }
type PropKey = keyof typeof properties
// One series per material class
const build_series = (x_prop: PropKey, y_prop: PropKey) =>
Object.entries(colors).map(([material, color]) => ({
x: all_data[material].map((row) => row[x_prop]),
y: all_data[material].map((row) => row[y_prop]),
label: material.charAt(0).toUpperCase() + material.slice(1),
point_style: { fill: color, radius: 4, fill_opacity: 0.7 },
markers: `points`,
}))
// Initial state
let x_key = $state<PropKey>(`density`)
let y_key = $state<PropKey>(`formation_energy`)
let series = $derived(build_series(x_key, y_key))
let loading_log = $state<string[]>([])
let error_count = $state(0)
let load_count = $state(0)
let load_start = $state(0)
// Caller-owned loading; only the latest result updates the selected properties
async function data_loader(
_axis: AxisKey,
property_key: string,
_signal: AbortSignal,
): Promise<PropKey> {
if (!Object.hasOwn(properties, property_key))
throw new Error(`Unknown property: ${property_key}`)
const key = property_key as PropKey
load_start = performance.now()
loading_log = [...loading_log, `⏳ Loading ${properties[key].label}...`]
// Variable delay (200-800ms) to simulate real network conditions
const delay = 200 + Math.random() * 600
await new Promise((resolve) => setTimeout(resolve, delay))
// 5% chance of simulated error
if (Math.random() < 0.05) {
error_count++
throw new Error(`Simulated network error for ${property_key}`)
}
return key
}
const axis_loader = create_axis_loader(data_loader)
onDestroy(axis_loader.cancel)
async function on_axis_change(axis: AxisKey, property_key: string): Promise<void> {
try {
const key = await axis_loader.load(axis, property_key)
if (key === undefined) return
load_count++
if (axis === `x`) x_key = key
if (axis === `y`) y_key = key
const elapsed = Math.round(performance.now() - load_start)
loading_log = [...loading_log, `✓ Loaded ${properties[key].label} (${elapsed}ms)`]
} catch (error) {
loading_log = [
...loading_log,
`❌ ${axis}-axis error (${property_key}): ${String(error)}`,
]
}
}
// Axis options from properties
const axis_options = Object.entries(properties).map(([key, prop]) => ({
key,
label: prop.label,
unit: prop.unit,
}))
</script>
<p>
<strong>Stress test:</strong> 240 points across 3 series. Click axis labels to switch
properties. ~5% of loads will fail to test error recovery.
</p>
<div class="stats">
<span>Loads: <strong>{load_count}</strong></span>
<span>Errors: <strong style="color: #e74c3c">{error_count}</strong></span>
</div>
<ScatterPlot
{series}
x_axis={{
label: `${properties[x_key].label} (${properties[x_key].unit})`,
options: axis_options,
selected_key: x_key,
}}
y_axis={{
label: `${properties[y_key].label} (${properties[y_key].unit})`,
options: axis_options,
selected_key: y_key,
}}
{on_axis_change}
legend={{ layout: `horizontal`, style: `justify-content: center` }}
style="height: 400px"
/>
<div class="log">
{#each loading_log.slice(-6) as msg, idx (idx)}
<div>{msg}</div>
{/each}
{#if loading_log.length === 0}
<div style="opacity: 0.6">Click an axis label to see loading activity</div>
{/if}
</div>Interactive Color Dimension with Dynamic ColorBar
Interactive axis labels plus an interactive ColorBar for 3-axis exploration. ColorBar dropdowns pick property and color scale. You can switch:
- X-axis property (click x-axis label)
- Y-axis property (click y-axis label)
- Color property (click ColorBar title/property dropdown)
- Color scheme (click ColorBar color scale dropdown)
Axis changes simulate delayed loading. Color property and palette changes use the already loaded data immediately.
Interactive example
svelte<script lang="ts">
import { onDestroy } from 'svelte'
import { ScatterPlot, create_axis_loader } from 'matterviz'
import { seeded_rng } from '#site/histogram-data.js'
type DataPoint = {
density: number
volume: number
formation_energy: number
bandgap: number
bulk_modulus: number
thermal_cond: number
}
// Generate correlated materials data
function generate_data(n_points: number, base_seed: number): DataPoint[] {
const rng = seeded_rng(base_seed)
const data: DataPoint[] = []
for (let idx = 0; idx < n_points; idx++) {
const base_density = 2 + rng() * 18
data.push({
density: base_density,
volume: 8 + (20 - base_density) * 2 + rng() * 5,
formation_energy: -4 + rng() * 8 - base_density * 0.1,
bandgap: Math.max(0, 5 - base_density * 0.2 + rng() * 3),
bulk_modulus: 20 + base_density * 10 + rng() * 50,
thermal_cond: 5 + base_density * 3 + rng() * 30,
})
}
return data
}
const all_data = generate_data(150, 12345)
// Property definitions with HTML sub/superscripts
const properties = {
density: { label: `Density ρ`, unit: `g·cm<sup>−3</sup>` },
volume: { label: `Volume V`, unit: `Å<sup>3</sup>/atom` },
formation_energy: { label: `Formation Energy E<sub>form</sub>`, unit: `eV/atom` },
bandgap: { label: `Band Gap E<sub>gap</sub>`, unit: `eV` },
bulk_modulus: { label: `Bulk Modulus K`, unit: `GPa` },
thermal_cond: { label: `Thermal Cond. κ`, unit: `W·m<sup>−1</sup>·K<sup>−1</sup>` },
}
// One committed palette drives both the chart's mapping and the ColorBar selection.
const color_scales = {
viridis: `interpolateViridis`,
plasma: `interpolatePlasma`,
inferno: `interpolateInferno`,
turbo: `interpolateTurbo`,
cool: `interpolateCool`,
}
const color_scale_options = Object.keys(color_scales).map((key) => ({
key,
label: key[0].toUpperCase() + key.slice(1),
}))
const metadata = all_data.map((row, idx) => ({ idx, ...row }))
const column = (key) => all_data.map((row) => row[key])
const point_style = { radius: 5, fill_opacity: 0.8, stroke: `white`, stroke_width: 0.5 }
// State
let x_key = $state(`density`)
let y_key = $state(`formation_energy`)
let color_key = $state(`bandgap`)
let color_scale_key = $state(`viridis`)
let series = $derived([
{
x: column(x_key),
y: column(y_key),
color_values: column(color_key),
point_style,
markers: `points`,
metadata,
},
])
let axis_switches = $state(0)
let color_switches = $state(0)
// Options for the x/y axis dropdowns and the ColorBar property dropdown
const axis_options = Object.entries(properties).map(([key, prop]) => ({ key, ...prop }))
// Load outside the chart; cancelled requests cannot publish stale data
async function axis_data_loader(axis, property_key, _signal) {
await new Promise((resolve) => setTimeout(resolve, 200 + Math.random() * 400))
return property_key
}
// Called after successful axis change - safe to update state
const axis_loader = create_axis_loader(axis_data_loader)
onDestroy(axis_loader.cancel)
async function handle_axis_change(axis, property_key) {
if (!(await axis_loader.load(axis, property_key))) return
axis_switches++
if (axis === `x`) x_key = property_key
if (axis === `y`) y_key = property_key
}
// All properties are already loaded; publish the new color property directly
function on_property_change(property_key) {
color_switches++
color_key = property_key
}
</script>
<p>
<strong>150 points</strong> with 3 interactive dimensions. Click axis labels to switch X/Y
properties. Click the ColorBar title to switch color property, or the color scale dropdown to
change the color scheme.
</p>
<div class="stats">
<span>Axis switches: <strong>{axis_switches}</strong></span>
<span>Color switches: <strong>{color_switches}</strong></span>
</div>
<ScatterPlot
{series}
x_axis={{
label: `${properties[x_key].label} (${properties[x_key].unit})`,
options: axis_options,
selected_key: x_key,
}}
y_axis={{
label: `${properties[y_key].label} (${properties[y_key].unit})`,
options: axis_options,
selected_key: y_key,
}}
on_axis_change={handle_axis_change}
color_scale={{ scheme: color_scales[color_scale_key] }}
color_bar={{
title: `${properties[color_key].label} (${properties[color_key].unit})`,
property_options: axis_options,
selected_property_key: color_key,
on_property_change,
color_scale_options,
selected_color_scale_key: color_scale_key,
on_color_scale_change: (key) => (color_scale_key = key),
}}
style="height: 450px"
legend={null}
/>Stress Test: Many Interpolated Fills
Several fill regions between series at different sample densities, to stress-test interpolation:
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Generate series with different densities and offsets
const colors = ['#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6']
const make_series = (n_points, offset, amplitude, color, label) => {
const step = 20 / (n_points - 1)
const x_vals = Array.from({ length: n_points }, (_, idx) => idx * step)
return {
x: x_vals,
y: x_vals.map((val) => offset + amplitude * Math.sin(val * 0.5 + offset * 0.2)),
label,
point_style: { fill: color, radius: 3 },
line_style: { color, width: 1.5 },
markers: 'line+points',
}
}
// Create 5 series with different sampling rates
const all_series = [
make_series(8, 4, 2, colors[0], '8 pts'),
make_series(15, 7, 2, colors[1], '15 pts'),
make_series(25, 10, 2, colors[2], '25 pts'),
make_series(12, 13, 2, colors[3], '12 pts'),
make_series(40, 16, 2, colors[4], '40 pts'),
]
// Create fills between each consecutive pair
const fill_regions = [
{
upper: { type: 'series', series_idx: 1 },
lower: { type: 'series', series_idx: 0 },
fill: 'rgba(231, 76, 60, 0.25)',
label: 'Fill 0-1',
curve: 'monotoneX',
},
{
upper: { type: 'series', series_idx: 2 },
lower: { type: 'series', series_idx: 1 },
fill: 'rgba(52, 152, 219, 0.25)',
label: 'Fill 1-2',
curve: 'monotoneX',
},
{
upper: { type: 'series', series_idx: 3 },
lower: { type: 'series', series_idx: 2 },
fill: 'rgba(46, 204, 113, 0.25)',
label: 'Fill 2-3',
curve: 'monotoneX',
},
{
upper: { type: 'series', series_idx: 4 },
lower: { type: 'series', series_idx: 3 },
fill: 'rgba(243, 156, 18, 0.25)',
label: 'Fill 3-4',
curve: 'monotoneX',
},
]
</script>
<ScatterPlot
series={all_series}
{fill_regions}
x_axis={{ label: 'X Value', range: [0, 20] }}
y_axis={{ label: 'Y Value', range: [0, 20] }}
style="height: 400px"
legend={{ layout: 'horizontal', style: 'justify-content: center;' }}
/>Y2 Axis Synchronization
When using dual y-axes (Y1 left, Y2 right), the sync property on y2_axis controls the Y2 axis range. Modes: 'synced' (Y2 has exact same range as Y1), 'align' (Y2 expands to show all data with a shared anchor point, default 0), or undefined/'none' (independent).
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
const n_points = 50
const time = Array.from({ length: n_points }, (_, idx) => idx * 0.5)
const temperature_data = {
x: time,
y: time.map((time_value) => 20 + 15 * Math.sin(time_value * 0.3) + Math.random() * 3),
label: `Temperature (°C)`,
point_style: { fill: `#e74c3c`, radius: 4 },
line_style: { color: `#e74c3c`, width: 2 },
markers: `line+points`,
y_axis: `y`,
}
const pressure_data = {
x: time,
y: time.map(
(time_value) => 100 + 30 * Math.sin(time_value * 0.3 + 0.5) + Math.random() * 5,
),
label: `Pressure (kPa)`,
point_style: { fill: `#3498db`, radius: 4 },
line_style: { color: `#3498db`, width: 2 },
markers: `line+points`,
y_axis: `y2`,
}
const sync_labels = {
none: `Independent`,
synced: `Synced`,
align: `Align 0`,
}
let sync_mode = $state(`none`)
</script>
<div class="demo-controls">
<strong>Y2 Sync:</strong>
{#each Object.entries(sync_labels) as [mode, label] (mode)}
<label><input type="radio" bind:group={sync_mode} value={mode} /> {label}</label>
{/each}
</div>
<ScatterPlot
series={[temperature_data, pressure_data]}
x_axis={{ label: `Time (s)` }}
y_axis={{ label: `Temperature (°C)`, color: `#e74c3c` }}
y2_axis={{
label: `Pressure (kPa)`,
color: `#3498db`,
sync: sync_mode,
}}
style="height: 400px"
/>Y2 Sync via PlotControls
Click the gear icon to access the Y2 Sync dropdown in PlotControls.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
const n_points = 30
const x_vals = Array.from({ length: n_points }, (_, idx) => idx)
const make_series = (label, color, y_axis, freq, offset, amp, noise) => ({
x: x_vals,
y: x_vals.map(
(coord_x) => offset + amp * Math.sin(coord_x * freq) + Math.random() * noise,
),
label,
y_axis,
markers: `line+points`,
point_style: { fill: color, radius: 4 },
line_style: { color, width: 2 },
})
const series = [
make_series(`Efficiency (%)`, `#e74c3c`, `y`, 0.2, 60, 20, 5),
make_series(`Yield (%)`, `#f39c12`, `y`, 0.15, 70, 15, 4),
make_series(`Throughput (units/hr)`, `#3498db`, `y2`, 0.25, 500, 200, 30),
{
...make_series(`Cost ($/unit)`, `#9b59b6`, `y2`, 0.18, 200, 100, 20),
line_style: { color: `#9b59b6`, width: 2, dash: `4 2` },
},
]
let y2_axis = $state({ label: `Secondary Metrics`, sync: `none` })
</script>
<ScatterPlot
{series}
x_axis={{ label: `Sample Index` }}
y_axis={{ label: `Percentage Metrics (%)` }}
bind:y2_axis
show_controls={true}
style="height: 450px"
/>Dual X-Axes (X2)
Plot two series with independent x-scales on the same chart. The primary x-axis (bottom) shows one unit while the secondary x2-axis (top) shows another. For inversely related quantities like wavelength (nm) and photon energy (eV) where E = 1240/λ, invert the x2 range so the axes align correctly: high energy at short wavelength (left) and low energy at long wavelength (right).
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
// Emission spectrum vs wavelength (bottom x-axis, nm)
const wavelengths = [380, 430, 480, 530, 580, 630, 680, 730, 780]
const intensity = wavelengths.map(
(wavelength) => 0.85 * Math.exp(-0.5 * ((wavelength - 550) / 80) ** 2),
)
const wavelength_series = {
x: wavelengths,
y: intensity,
label: `Wavelength (nm)`,
markers: `line+points`,
line_style: { color: `#7c3aed`, width: 2 },
point_style: { fill: `#7c3aed`, radius: 5 },
}
// Same spectrum plotted against energy (top x2-axis, eV); E = 1240 / λ
const energy_series = {
x: wavelengths.map((wavelength) => 1240 / wavelength),
y: intensity,
label: `Energy (eV)`,
x_axis: `x2`,
markers: `line+points`,
line_style: { color: `#ea580c`, width: 2 },
point_style: { fill: `#ea580c`, radius: 5 },
}
</script>
Same emission spectrum plotted on two x-scales. Bottom: wavelength in nm (purple, increasing
left→right). Top: photon energy in eV (orange, decreasing left→right via inverted `range`). The
x2 range is set high→low so 380 nm aligns with 3.26 eV at the left edge.
<ScatterPlot
series={[wavelength_series, energy_series]}
x_axis={{ label: `Wavelength (nm)`, color: `#7c3aed` }}
x2_axis={{ label: `Energy (eV)`, color: `#ea580c`, range: [3.5, 1.4] }}
y_axis={{ label: `Intensity (a.u.)` }}
style="height: 400px"
/>Unified Legend, Colorbar, and Annotation Placement
The legend and colorbar are solved together against measured footprints and data density. Reference-line annotations without an explicit position or side then treat those decorations as exclusions, so all three remain readable as the data moves.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
const cluster = (center_x, center_y, phase) =>
Array.from({ length: 32 }, (_, point_idx) => {
const angle = point_idx * 2.399 + phase
const radius = 4 + (point_idx % 8) * 1.4
return {
x: center_x + Math.cos(angle) * radius,
y: center_y + Math.sin(angle) * radius,
score: point_idx / 31,
}
})
let center_x = $state(72)
let center_y = $state(72)
let series = $derived(
[
{ label: `Candidate set A`, color: `#4c6ef5`, points: cluster(center_x, center_y, 0) },
{
label: `Candidate set B`,
color: `#f59f00`,
points: cluster(100 - center_x, 100 - center_y, 1.2),
},
].map(({ label, color, points }) => ({
label,
x: points.map((point) => point.x),
y: points.map((point) => point.y),
color_values: points.map((point) => point.score),
markers: `points` as const,
point_style: { fill: color, radius: 5, stroke: `white`, stroke_width: 0.5 },
})),
)
const ref_lines = [
{
type: `horizontal` as const,
y: 50,
style: { color: `#e03131`, width: 2, dash: `7 4` },
annotation: { text: `Review threshold` },
},
]
</script>
<div class="demo-controls">
<label
>Cluster x: {center_x}<input type="range" bind:value={center_x} min="18" max="82" /></label
>
<label
>Cluster y: {center_y}<input type="range" bind:value={center_y} min="18" max="82" /></label
>
</div>
<ScatterPlot
{series}
{ref_lines}
x_axis={{ label: `Composition coordinate`, range: [0, 100] }}
y_axis={{ label: `Stability score`, range: [0, 100] }}
color_scale={{ scheme: `interpolateViridis` }}
color_bar={{ title: `Local score`, responsive: true }}
legend={{ layout: `horizontal`, layout_tracks: `auto`, responsive: true, draggable: false }}
show_controls={false}
style="height: 460px"
/>Metadata-Driven Axis Assignment
Series unit metadata groups compatible values onto one y-axis. axis_group explicitly separates values that need an independent scale even when the units match; labels and a logarithmic scale are then inferred from the visible series.
Interactive example
svelte<script lang="ts">
import { ScatterPlot } from 'matterviz'
const iterations = Array.from({ length: 10 }, (_, iteration_idx) => iteration_idx)
let split_residual = $state(true)
let series = $derived([
{
x: iterations,
y: iterations.map((iteration_idx) => -18.4 - 2.1 * (1 - Math.exp(-iteration_idx / 2))),
label: `Total energy`,
unit: `eV`,
markers: `line+points` as const,
line_style: { color: `#4c6ef5`, width: 2 },
point_style: { fill: `#4c6ef5` },
},
{
x: iterations,
y: iterations.map((iteration_idx) => 0.2 * 10 ** -iteration_idx),
label: `SCF residual`,
unit: `eV`,
axis_group: split_residual ? `scf-residual` : undefined,
markers: `line+points` as const,
line_style: { color: `#f03e3e`, width: 2 },
point_style: { fill: `#f03e3e` },
},
])
</script>
<label
><input type="checkbox" bind:checked={split_residual} /> Give the residual an independent
axis group</label
>
<ScatterPlot
{series}
x_axis={{ label: `Self-consistent field iteration` }}
legend={{ draggable: false }}
show_controls={false}
style="height: 420px"
/>