help for sparkta

sparkta -- Interactive self-contained HTML charts from Stata

(View online documentation and examples)

Syntax

sparkta varlist [if] [in] [, options]

where options include:

Option Description

over(varname) group chart by categorical variable

by(varname) separate panel per group

filters(varlist) add interactive filter dropdowns

sliders(varlist) add dual-handle range sliders

type(charttype) chart type (default bar)

stat(string) statistic to plot (default mean)

export(filepath) save HTML to file

offline bundle JS inside HTML (no CDN needed)

xtitle(s) ... axis titles, ranges, scales, ticks

title(s) ... titles, colors, themes, fonts

yline(v) ... reference lines, bands, points, ellipses

fit(type) scatter fit line: lfit qfit lowess exp log power ma

bins(#) ... histogram, box plot, and violin options

cilevel(#) ... confidence interval options

For a complete option list see Options.

Description

sparkta converts Stata data into a self-contained interactive HTML
chart with one command. The .html file opens in any browser, requires
no server and no software on the recipient's end -- email it and the
interactivity travels with it.

Every chart includes a collapsible statistics panel (N, mean, median, SD,
min, max, CV, sparklines) that updates live when a filter or slider changes.

Requirements: Stata 17+. Place sparkta.jar in your Stata
personal ado folder or working directory.

Quick start

All examples use Stata's built-in auto dataset.

sysuse auto, clear

sparkta price, over(rep78) mean price by repair record

sparkta price mpg, type(scatter) scatter plot

sparkta price, type(cibar) over(rep78) CI bar chart

sparkta price, over(rep78) filters(foreign) with live filter

sparkta price, over(rep78) sliders(mpg) with range slider

sparkta price, type(violin) over(rep78) theme(dark_neon) violin, dark theme

sparkta price mpg, type(scatter) fit(lowess) fitci fit line + CI band

For more examples see Examples.

Contents

Varlist what goes in varlist by chart type

Chart types all 20+ types with descriptions

Themes background and color palettes

Options complete option reference

Examples runnable examples by category

Statistics panel what the panel shows and how

Offline mode bundled HTML for air-gapped use

Statistical methods formulas, references, plugins

Common mistakes errors most new users make

Known limitations chart type restrictions

Memory and large datasets java_heapmax settings

Varlist

The variable(s) before the comma are what gets measured.

bar, hbar, stacked* one or more numeric variables; stat() applied per group

line, area, stacked* one or more numeric variables plotted as series

scatter y first, then x: sparkta price mpg, type(scatter)

bubble y, x, size: sparkta price mpg weight, type(bubble)

histogram exactly one numeric variable

boxplot, hbox one or more numeric variables

violin, hviolin one numeric variable; over() for groups

cibar, ciline one numeric variable; over() required

pie, donut one variable (slice sizes), or omit for frequency counts

over() vs by() vs filters():
over() puts all groups on one chart.
by() creates separate panels.
filters() lets the viewer switch groups without re-running Stata.
Combine over() and by(): by() makes panels, over() groups series inside each.

Chart types

Specify with type(charttype). Default is bar.

Bar / column

bar vertical bars -- mean (or chosen stat) per group

hbar horizontal bars

stackedbar stacked vertical bars

stackedhbar stacked horizontal bars

stackedbar100 100% stacked bars

stackedhbar100 100% stacked horizontal

Line / area

line line chart

area filled area

stackedline stacked lines

stackedarea stacked areas

Distributions

histogram frequency/density histogram

boxplot standard box plot

hbox horizontal box plot

violin violin plot

hviolin horizontal violin

Relationships

scatter scatter plot; add fit() for a fitted line

bubble bubble chart; third variable sets bubble size

Proportions

pie pie chart

donut donut chart

Statistical CI charts

cibar bars with 95% CI error bars; requires over()

ciline line with 95% CI band; requires over()

Themes

theme(string) accepts a background keyword, a palette name,
or a compound background_palette:

Backgrounds

default white page, default colors

dark dark page background

light light gray page background

Color palettes

tab1 Tableau 10

tab2 ColorBrewer Set1

tab3 ColorBrewer Dark2

cblind1 Okabe-Ito colorblind-safe

viridis perceptually uniform

neon bright saturated (best on dark)

swift_red warm earth tones

Compound (background + palette)

dark_tab1 dark background + Tableau 10

dark_tab2 dark background + ColorBrewer Set1

dark_tab3 dark background + ColorBrewer Dark2

dark_cblind1 dark background + Okabe-Ito

dark_viridis dark background + viridis

dark_neon dark background + neon (recommended)

dark_swift_red dark background + swift_red

light_tab1 light background + Tableau 10

light_tab2 light background + ColorBrewer Set1

light_tab3 light background + ColorBrewer Dark2

light_cblind1 light background + Okabe-Ito

light_viridis light background + viridis

light_neon light background + neon

light_swift_red light background + swift_red

colors() always overrides any palette.
Use spaces to separate colors: colors(#e41a1c #377eb8 #4daf4a)

Options

Click any option group to jump to its documentation.
Chart-type-specific options are grouped under the chart type.

Option group Key options

Applied to all chart types

Grouping and panels over() by() filters() sliders() layout()

Aggregation stat() sortgroups() nomissing showmissing nostats

Axes xtitle() ytitle() xrange() yrange() xtype() y2()

Appearance title() theme() colors() opacity() gradient

Ref. lines and annotations yline() xline() yband() apoint()

Export and data handling export() offline download novaluelabels

Bar and line charts

bar hbar stackedbar* see Appearance, Axes

Bar appearance barwidth() bargroupwidth() borderradius() horizontal stacked

Line and area linewidth() lpattern() smooth() fill areaopacity() spanmissing

Scatter and bubble

scatter bubble fit lines, marker labels, point styling

Fit lines fit(lfit|qfit|lowess|exp|log|power|ma) fitci

Marker labels mlabel() mlabpos() mlabvposition()

Point styling pointsize() pointstyle() nopoints pointhoversize()

CI charts

cibar ciline cilevel() cibandopacity() -- over() required

Histogram

histogram bins() histtype(frequency|density|fraction)

Box and violin

boxplot violin hbox hviolin whiskerfence() bandwidth() mediancolor() meancolor()

Pie and donut

pie donut cutout() rotation() circumference() pielabels sliceborder()

Complete syntax reference (all 149 options):

Essential
type(charttype) chart type; see Chart types

over(varname) group by variable, all groups on one chart

by(varname) separate panel per group

filters(varlist) add live interactive filter dropdowns

sliders(varlist) add dual-handle range sliders

title(string) chart title

export(path) save HTML to file instead of opening browser

offline bundle all JS inside the HTML for air-gap use

Grouping / panels
layout(string) panel layout: vertical | horizontal | grid

sortgroups(string) group order: asc | desc

nomissing exclude missing values from grouping variables

showmissing include (Missing) as an explicit group

nostats suppress the summary statistics panel

Axes
xtitle(string) x-axis title

ytitle(string) y-axis title

xrange(min max) x-axis min and max

yrange(min max) y-axis min and max

xtype(string) scale: linear | log | category | time

ytype(string) scale: linear | logarithmic

yreverse reverse y-axis direction

xreverse reverse x-axis direction

noticks hide tick marks

ygrace(#) proportional padding above y-max (e.g. 0.1 = 10%)

xticks(list) pin x tick positions, pipe-sep

yticks(list) pin y tick positions, pipe-sep

xlabels(list) custom x tick labels, pipe-sep

ylabels(list) custom y tick labels, pipe-sep

xtickcount(#) x-axis tick count

ytickcount(#) y-axis tick count

xtickangle(#) x tick label rotation degrees

ytickangle(#) y tick label rotation degrees

y2(varlist) secondary y-axis variables

Chart appearance
theme(string) background / palette; see Themes

colors(list) series colors, pipe-separated CSS values

bgcolor(color) page background color

opacity(#) fill opacity 0-1 (default 0.85)

gradient gradient fill using palette colors

gradcolors(c1|c2) custom gradient start|end colors

download add PNG download button

datalabels show value labels on bars/slices

Labels / legend
subtitle(string) secondary heading

note(string) italic note below chart

leglabels(list) rename legend entries, pipe-separated

relabel(list) rename over() group labels on axis + legend

legend(pos) legend position: top|bottom|left|right|none

nolegend suppress legend

novaluelabels use raw numeric codes instead of Stata value labels

Lines and points
linewidth(#) line width px (default 2)

lpattern(string) line style: solid|dash|dot|dashdot

lpatterns(list) per-series patterns, pipe-separated

smooth(#) line smoothing 0-1

nopoints hide point markers

pointsize(#) point radius px (default 4)

pointstyle(string) shape: circle|cross|rect|star|triangle

spanmissing connect lines across missing values

stepped(string) step function: before|after|middle

Bars
horizontal horizontal bars

stacked stack series

barwidth(#) bar width as proportion 0-1

borderradius(#) bar corner radius px

Scatter / fit
fit(type) scatter fit line: lfit|qfit|lowess|exp|log|power|ma

fitci add 95% CI band to fit line (all fit types)

mlabel(varname) label scatter points with a variable

mlabpos(#) label position 0-59 (minute-clock; default=above point, 15=right, 30=below)

mlabvposition(var) per-observation label position variable (0-59)ariable (0-59 numeric var)

Statistical
stat(string) statistic: mean|sum|count|min|max|pct

cilevel(#) any integer 1-99 (default 95; common: 90, 95, 99)

whiskerfence(#) IQR multiplier for box plot whiskers (default 1.5)

bins(#) number of histogram bins

histtype(string) histogram scale: frequency|density|fraction

bandwidth(#) violin KDE bandwidth

mediancolor(color) box/violin median marker color

meancolor(color) box/violin mean marker color

Reference lines / annotations
yline(values) horizontal/vertical reference lines, pipe-separated

ylinecolor(colors) yline colors, pipe-sep

xlinecolor(colors) xline colors, pipe-sep

ylinelabel(texts) yline labels, pipe-sep

xlinelabel(texts) xline labels, pipe-sep

yband(lo hi) horizontal shaded band

xband(lo hi) vertical shaded band; pipe-sep for multiple

ybandcolor(colors) yband fill colors, pipe-sep

xbandcolor(colors) xband fill colors, pipe-sep

apoint(y x ...) annotation points: space-sep y x pairs

alabelpos(coords) annotation labels: y x pos (minute-clock)te-clock), pipe-sep sets

alabeltext(texts) annotation label texts, pipe-separated

aellipse(coords) annotation ellipses (ymin xmin ymax xmax), pipe-sep sets

Tooltips / styling
tooltipformat(string) number format: currency|percent|integer|auto

tooltipmode(string) hover mode: point|index|nearest

tooltipbg(color) tooltip background color

titlesize(string) title font size

titlecolor(color) title color

xlabsize(string) x tick label font size

ylabsize(string) y tick label font size

animduration(#) animation duration ms (default ~1000)

aspect(#) width/height ratio

Labels and text
title(string) main chart heading

subtitle(string) secondary heading below title

note(string) italic note below chart

caption(string) small caption below note

notesize(string) font size for note and caption (CSS value)

datalabels show value labels on bars/slices

Chart behaviour
type(charttype) chart type; see Chart types

horizontal horizontal bars (alias for type(hbar))

stacked stack multiple series

fill fill area under line (alias for type(area))

areaopacity(#) area fill opacity 0-1 (default 0.35)

spanmissing connect lines across missing values

nopoints hide point markers on line/area charts

pointborderwidth(#) point border width px (default 1)

pointrotation(#) point rotation degrees (default 0)

pointhoversize(#) point radius on hover px (default pointsize+2)

gradient gradient fill using palette colors

gradcolors(c1|c2) custom gradient: start|end color

download PNG download button in chart header

fitci 95% CI band around scatter fit line

padding(#) inner chart padding px

bargroupwidth(#) bar group width proportion 0-1

Data and missing values
nostats suppress the summary statistics panel

novaluelabels use raw numeric codes instead of Stata value labels

nomissing exclude missing values from grouping variables

Axis lines and grid
yreverse reverse y-axis direction

xreverse reverse x-axis direction

noticks hide axis tick marks (labels remain)

ystart(zero) anchor y-axis at zero

yrange(min max) y-axis min and max

xstepsize(#) x-axis tick interval

ystepsize(#) y-axis tick interval

ytickangle(#) y tick label rotation degrees

ytickcount(#) approximate y tick count

yticks(list) pin y tick positions, pipe-sep

xgridlines(on|off) vertical grid lines

ygridlines(on|off) horizontal grid lines

xborder(on|off) x-axis border line

yborder(on|off) y-axis border line

gridcolor(color) grid line color

gridopacity(#) grid line opacity 0-1 (default 0.15)

xlabels(list) custom x tick labels, pipe-sep

ylabels(list) custom y tick labels, pipe-sep

ytitle(string) y-axis label

y2range(min max) secondary y-axis min and max

y2title(string) secondary y-axis label

Reference lines (continued)
xline(values) vertical reference lines, pipe-sep

xlinecolor(colors) xline colors, pipe-sep

xlinelabel(texts) xline labels, pipe-sep

xband(lo hi) vertical shaded band; pipe-sep for multiple

xbandcolor(colors) xband fill colors, pipe-sep

Annotation sub-options
apointcolor(colors) annotation point colors, pipe-sep

apointsize(#) annotation point radius px (default 8)

aellipsecolor(colors) ellipse fill colors, pipe-sep

aellipseborder(colors) ellipse border colors, pipe-sep

alabelgap(#) annotation label offset distance px (default 15)

alabelfs(#) annotation label font size px (default 12)

Legend sub-options
nolegend suppress legend entirely

legtitle(string) legend title

legsize(#) legend font size px (default 10)

legboxheight(#) legend color swatch height px

legcolor(color) legend text color

legbgcolor(color) legend background color

Colors and background
bgcolor(color) page background color

plotcolor(color) chart area background color

theme(string) background / palette; see Themes

Font styling
titlecolor(color) title text color

subtitlesize(string) subtitle font size

subtitlecolor(color) subtitle text color

xtitlesize(string) x-axis title font size

xtitlecolor(color) x-axis title color

ytitlesize(string) y-axis title font size

ytitlecolor(color) y-axis title color

xlabcolor(color) x tick label color

ylabcolor(color) y tick label color

xlabsize(string) x tick label font size

ylabsize(string) y tick label font size

Tooltip sub-options
tooltipborder(color) tooltip border color

tooltipfontsize(#) tooltip font size px

tooltippadding(#) tooltip padding px

tooltipposition(string) tooltip anchor: average|nearest

Animation
animate(string) speed: fast|slow|none

animdelay(#) delay before animation starts (ms)

easing(string) animation easing function

Pie and donut
cutout(#) donut hole size 0-99 (default 55)

rotation(#) starting angle degrees (default 0=top)

circumference(#) arc degrees drawn (default 360=full circle)

sliceborder(#) border width between slices px (default 1)

hoveroffset(#) slice pop-out on hover px (default 8)

pielabels show percentage labels on slices

meancolor(color) mean line color in box/violin plots

Offline and CI
offline bundle all JS inside the HTML file

cibandopacity(#) CI band fill opacity 0-1 (ciline only)

Export
export(path) save HTML to file; path must end in .html

Grouping, panels, and filtering

over(varname [, showmissing]) The most-used option in sparkta.
Groups the chart by a categorical variable so each group becomes a separate
series on the same chart. Value labels are used automatically when present.

over() and by() can be used together for most chart types.
For example, over(rep78) by(foreign) creates one panel per foreign value,
each showing grouped bars by repair record. The exception is pie and
donut, where combining them is not permitted.

Suboption showmissing includes observations where varname is missing
as an explicit (Missing) group, displayed last regardless of sortgroups().
Without showmissing, missing observations are silently excluded.

Example: sparkta price weight, type(bar) over(foreign) -- one bar per variable per origin group.

by(varname [, showmissing]) Creates separate chart panels for each value
of varname. Suboption showmissing adds a (Missing) panel
for observations where varname is missing.

by() and over() can be combined for most chart types (not pie/donut).
When combined, by() creates the panels and over() groups series within each panel.

Examples:

sparkta price, type(bar) by(foreign) layout(grid) -- one panel per origin, 2-column grid

sparkta price, type(bar) over(rep78) by(foreign) -- grouped bars by repair record, separate panel per origin

layout(string) Arrangement of by() panels. Options:
vertical (default, stacked) | horizontal (side by side) |
grid (2-column grid). Only applies when by() is used.

Example: sparkta price, by(rep78) layout(grid)

filters(varname [, showmissing]) Adds an interactive dropdown below the
chart letting viewers filter the data by values of varname without
reloading. The chart updates live. Suboption showmissing adds a
(Missing) option for observations where varname is missing.

Example: sparkta price, over(rep78) filter(foreign) -- viewer can toggle between Domestic and Foreign without re-running Stata.

filters(varname [, showmissing]) Second independent interactive filter
dropdown. Requires filter() to also be specified. Supports showmissing.

Example: sparkta price weight, over(rep78) filter(foreign) filter2(rep78)

sortgroups(string) Controls the order of over() and by()
group labels. Options: asc | desc.
When omitted, groups are sorted ascending (numeric labels sort numerically;
string labels sort alphabetically). Filter dropdown options are always
sorted ascending and are unaffected.

Example: sparkta price, over(rep78) sortgroups(desc) -- highest repair-record group shown first.

nostats Suppresses the summary statistics panel below the chart.

What gets plotted -- stat()

stat(string) The statistic plotted on the y-axis for bar and line charts.
Default is mean -- sparkta always shows group averages unless you say otherwise.
Options: mean | sum | count | median |
min | max. For pie/donut: pct (default, percentage share) |
sum (raw totals).

When over() is specified, one value is computed per group.
When over() is omitted, one value is computed per variable in
varlist and each variable becomes a separate bar or point.

Not applicable to boxplot and violin. These chart types always show
the full distribution. Specifying stat() with type(boxplot) or
type(violin) produces an error (unless stat(mean) is given,
which is silently accepted but has no effect).

Examples:

sparkta price, over(rep78) stat(median) -- median price per repair-record group

sparkta price, over(rep78) stat(count) -- number of cars per group

sparkta price, type(pie) over(rep78) stat(sum) -- pie slices as raw totals

cutout(#) Donut hole size as a percentage of the chart radius.
Default 55. Range 0-99.

rotation(#) Starting angle in degrees for pie/donut slices. Default 0
(top). Use -90 to start at the left.

circumference(#) Total arc in degrees rendered by pie/donut.
Default 360 (full circle). A semicircle (180) combined with
rotation(-90) creates a gauge-style half-donut chart.

Example -- half-donut gauge:

sparkta price, type(donut) over(rep78) circumference(180) rotation(-90)

sliceborder(#) Border width between pie/donut slices in pixels. Default 1.

hoveroffset(#) Distance slices pop out when hovered, in pixels. Default 8.

Scatter labels

mlabel(varname) Label each scatter point with the value of varname.
Accepts string or numeric variables. Long labels are truncated automatically.
Requires type(scatter) or type(bubble).

mlabpos(#) Position of the scatter marker label, specified as a
minute-clock direction (0-59). When omitted, labels appear above the point
(equivalent to pos = 0 on a clock face, which maps to "top" in Chart.js).
Common values: 15 = right, 30 = below, 45 = left, 0 = centered on point.

mlabvposition(varname) Per-observation label position. Numeric variable
with values 0-59 (minute-clock), one per row. Overrides mlabpos() for
individual points. Useful when labels would otherwise overlap.
Requires mlabel() and type(scatter) or type(bubble).

Example -- label points by make with custom positions:

sparkta price mpg, type(scatter) mlabel(make)

Fit lines and CI bands

fit(type) Overlay a fitted curve on a scatter chart.
Types: lfit (linear), qfit (quadratic), lowess
(locally weighted smoother), exp (exponential y=ae^bx),
log (logarithmic y=a+b*ln(x)), power (y=ax^b),
ma (5-point moving average). Fit lines are computed in Stata before
the chart is built and recomputed automatically when a slider changes.

fitci Add a 95% confidence band around the fit line.
Supported for lfit, qfit, exp, log,
power. CI is symmetric on the modelled scale and, for
exp and power, back-transformed to the original scale
(producing an asymmetric band, wider above the line than below).

Examples:

sparkta price mpg, type(scatter) fit(lfit) fitci

sparkta price mpg, type(scatter) fit(qfit) fitci sliders(mpg)

sparkta price mpg, type(scatter) over(foreign) fit(lfit)

CI charts

cilevel(#) Confidence level for cibar and ciline charts.
Default is 95. Accepts any integer from 1 to 99.
The CI formula is mean +/- t* x (SD/sqrt(N)) where t* uses the
t-distribution with N-1 degrees of freedom.

Confidence intervals are computed as mean +/- t * SE where SE = SD / sqrt(n)
and t is the two-tailed t-critical value with n-1 degrees of freedom.
Groups with fewer than 2 observations are omitted.
For df > 120 the standard normal z-critical value is used.

cibandopacity(#) Opacity of the CI shaded band for ciline charts.
Default is 0.18. Range 0-1.
Example: cibandopacity(0.05) for a faint band; cibandopacity(0.35)
for a more prominent band.

Histogram

bins(#) Number of bins. Must be an integer of 2 or greater. If omitted,
bins are determined by Sturges' rule: ceil(log2(n) + 1), clamped to [5, 50].
Start with the default; fewer bins reveal broad shape, more reveal fine structure.

Example: sparkta price, type(histogram) bins(20)

histtype(string) Y-axis metric.

density (default) count/(n*binWidth). Area sums to 1. Matches Stata twoway histogram default.

frequency Raw observation count per bin.

fraction Proportion of observations: count / n.

Examples:

sparkta price, type(histogram) histtype(density) -- area sums to 1, comparable across groups

sparkta price, type(histogram) histtype(frequency) -- raw counts, easiest to interpret

histogram does not support over(). Use by() to produce
separate histograms per group.

Box plots and violin charts

whiskerfence(#) Sets the Tukey IQR multiplier k used to compute whisker
fences. The lower fence is Q1 - k*IQR and the upper fence is Q3 + k*IQR.
Observations outside these fences are plotted as outlier dots.
Default is 1.5 (standard Tukey fence, matches Stata graph box).
Use a larger value (e.g. 3) to show fewer outliers; a smaller value
(e.g. 1) to show more.

Examples:

sparkta price, type(boxplot) over(rep78) whiskerfence(1.5) -- standard Tukey (default)

sparkta price, type(boxplot) over(rep78) whiskerfence(3) -- extreme-value fences, fewer outliers shown

mediancolor(string) Override the automatic median marker color with a
specific CSS color (hex, RGB, or named). For boxplot and hbox, the
median is shown as a horizontal line; for violin and hviolin, as a
diamond. By default, the color is chosen automatically based on the average
luminance of the fill colors: dark fills get a white marker, light fills get
a dark marker.

meancolor(string) Override the automatic mean marker color. The mean is
always shown as a filled circle (dot). Like mediancolor(), the default
is chosen from fill luminance. Use this option to set a specific color.

Example: sparkta price, type(boxplot) over(rep78) mediancolor(#e74c3c) meancolor(#2980b9)

bandwidth(#) KDE bandwidth for violin and hviolin charts.
Controls the smoothness of the estimated density curve: larger values produce
smoother, wider shapes; smaller values produce more peaked, data-hugging shapes.
If omitted, Silverman's rule of thumb is applied automatically:
h = 0.9 * min(SD, IQR/1.34) * n^(-1/5).

Example: bandwidth(2000) for a price variable measured in dollars.

Legend. Both chart types display an inline canvas legend in the top-right
corner of the chart area. For boxplot: Median, Mean, IQR Box, Whiskers,
and Outlier symbols. For violin: Median, Mean, IQR Box, Whiskers, and
KDE Shape symbols.

Violin animation. Violin charts animate on load (shapes grow in from flat)
and on filter change (shapes tween smoothly to the new distribution). This
animation is driven by a custom requestAnimationFrame loop and is not affected
by the animate() option.

Statistical formulas. All statistics (Q1, Q3, median, mean, whiskers)
match Stata summarize, detail output exactly, using the formula
h = (n+1)*p/100 with linear interpolation between adjacent order statistics.

Reference lines and annotations

yline(values) Draw one or more horizontal reference lines at the given
y-axis values. Pipe-separated. Works on all chart types that have a numeric y-axis.

Examples:

sparkta price, over(rep78) yline(6165) -- single line at the overall mean

sparkta price, over(rep78) yline(5000|10000) ylinecolor(red|blue) ylinelabel(Low|High) -- two colored and labeled lines

xline(values) Draw vertical reference lines at the given x-axis values.
Pipe-separated. Only meaningful on charts with a numeric x-axis
(scatter, bubble, line, area, ciline, histogram).
Silently ignored for bar, horizontal bar, CI bar, boxplot, and violin charts
(categorical x-axis).

ylinecolor(colors) Colors for each yline, pipe-separated CSS colors.
Cycles if fewer colors than lines. Default: rgba(150,150,150,0.8).

xlinecolor(colors) Colors for each xline. Same default.

ylinelabel(texts) Text label for each yline, pipe-separated.
An empty entry (two consecutive pipes) suppresses the label for that line.
Example: ylinelabel(Mean|Upper bound).

xlinelabel(texts) Text label for each xline. Same behavior.

yband(pairs) Draw one or more horizontal shaded bands. Each band is
specified as lo hi (two space-separated y values); multiple bands are
pipe-separated.

Examples:

sparkta price, over(rep78) yband(4000 8000) -- one shaded band

sparkta price, over(rep78) yband(4000 8000|10000 14000) ybandcolor(rgba(0,200,0,0.1)|rgba(200,0,0,0.1)) -- two differently colored bands

xband(pairs) Vertical shaded bands. Same format as yband().
Suppressed on categorical x-axis charts (same rules as xline()).

ybandcolor(colors) Fill color for each yband, pipe-separated.
Default: rgba(150,150,150,0.12). Cycles if fewer colors than bands.

xbandcolor(colors) Fill color for each xband. Same default.

apoint(coords) Draw annotation point markers at specific coordinates.
Format: space-separated y x pairs, following Stata scattteri convention.
Example: apoint(15000 25 20000 30) places markers at (y=15000, x=25)
and (y=20000, x=30). Note: y comes before x, matching Stata scattteri convention.

Example -- highlight two points on a scatter:

sparkta price mpg, type(scatter) apoint(4099 22 15906 12) apointcolor(red|navy)

apointcolor(colors) Colors for annotation points, pipe-separated.
Cycles. Default: rgba(255,99,132,0.8).

apointsize(#) Radius in pixels for all annotation points. Default 8.

alabelpos(coords) Place annotation text labels at specific coordinates.
Format: pipe-separated entries of y x or y x pos, where pos
is a minute-clock direction (0-59) controlling where the label appears
relative to the coordinate point:

0 Centered on the point (Stata mlabpos(0) equivalent; gap ignored)

15 Right of point

30 Below point

45 Left of point

60 Above point

Any integer from 0 to 60 is accepted, following the minute hand exactly.
(60 wraps back to above, same direction as approaching 12 on a clock face.)
Example: alabelpos(15000 25 15|20000 30 30) places the first label
to the right of (15000, 25) and the second label below (20000, 30).
Must be paired with alabeltext().

Example -- two labels, first to the right, second below:

sparkta price mpg, type(scatter) alabelpos(4099 22 15|15906 12 30) alabeltext(Economy|Luxury)

alabeltext(texts) Text content for annotation labels, pipe-separated.
Must have the same number of entries as alabelpos().
Example: alabeltext(Recession start|Recovery peak).

alabelfs(#) Font size in pixels for all annotation labels. Default 12.
(Renamed from alabelfontsize() in v3.5.108 -- original 15-character name
caused option not allowed errors on Windows Stata.)

alabelgap(#) Pixel distance from the coordinate point to the label.
Default 15. Only meaningful when the minute-clock direction in alabelpos()
is non-zero; direction 0 always centers the label regardless of gap.
One value applies to all labels. Example: alabelgap(20).

aellipse(quads) Draw annotation ellipses defined by bounding boxes.
Each ellipse is specified as four space-separated values ymin xmin ymax xmax;
multiple ellipses are pipe-separated.
Example: aellipse(10000 20 20000 30) draws one ellipse;
aellipse(10000 20 20000 30|5000 10 8000 15) draws two.

Example -- highlight a cluster on a scatter plot:

sparkta price mpg, type(scatter) aellipse(3000 25 6000 35) aellipsecolor(rgba(255,165,0,0.15)) aellipseborder(orange)

aellipsecolor(colors) Fill color per ellipse, pipe-separated.
Default: rgba(99,132,255,0.15).

aellipseborder(colors) Border color per ellipse, pipe-separated.
Default: rgba(99,132,255,0.6).

Chart type restrictions. Annotations are suppressed entirely for
pie and donut charts. Vertical annotations (xline,
xband) are silently suppressed for bar, horizontal bar, CI bar,
boxplot, and violin charts (categorical x-axis). All other annotation
types work on all numeric-axis chart types. For histogram,
xline and xband use fractional bin-index interpolation to
place marks at the correct proportional position across the numeric range.

Requires. The annotation plugin (chartjs-plugin-annotation@3.0.1)
is loaded from CDN automatically when any annotation option is specified.
For offline use, the plugin is bundled in sparkta.jar.

Offline mode

offline Embed all JavaScript libraries directly inside the HTML file
so the output requires no internet connection to open.

How it works. By default, sparkta generates a compact HTML file
that loads Chart.js from a CDN when opened in a browser. With offline,
the entire Chart.js library and all plugins are embedded inside the HTML at
generation time. The result is a single file that renders correctly on any
machine, anywhere, with no network request of any kind.

Data privacy and confidentiality. When your chart contains sensitive or
restricted data, the offline option gives you full control. No data ever
leaves the HTML file, no CDN is contacted when the file opens, and the chart
can be shared, archived, or presented on a machine with no internet access.
Particularly recommended for clinical, financial, or institutional data where
external network requests must be avoided.

Reproducibility. An offline HTML file is a permanent, self-contained
snapshot of both the chart rendering engine and the data at the time of
generation. It will render identically in any browser years from now,
independent of CDN availability, library version changes, or network conditions.
Suitable for inclusion in reproducibility archives and supplementary materials.

File size. The offline HTML is larger (~250-320 KB vs ~50 KB
for an online file) but functionally identical in all other respects.

Requirement. The JS libraries must be bundled in sparkta.jar
at compile time. Run fetch_js_libs.sh (Unix/Mac) or
fetch_js_libs.bat (Windows) from the java/ folder, then
recompile. See the repository README for step-by-step instructions.

Axes

xtitle(string) Label for the x-axis.

ytitle(string) Label for the y-axis.

Example: sparkta price mpg, type(scatter) xtitle(Mileage (mpg)) ytitle(Price (USD))

xrange(min max) X-axis minimum and maximum. Example: xrange(0 100).

yrange(min max) Y-axis minimum and maximum. Example: yrange(0 10000).

ystart(zero) Force the y-axis to begin at zero.
The only accepted value is zero. Incompatible with ytype(logarithmic).
Useful when Chart.js auto-scales to a non-zero minimum, making differences look larger than they are.

Example: sparkta price, over(rep78) ystart(zero)

xtype(string) X-axis scale type. Options: linear (default) |
logarithmic | category | time.

ytype(string) Y-axis scale type. Options: linear (default) |
logarithmic.

Example: sparkta price mpg, type(scatter) ytype(logarithmic) -- compresses right-skewed price values for cleaner scatter patterns.

y2(varlist) One or more variables to plot on the right (secondary) y-axis.
Each variable must also appear in varlist. The right axis is independently
scaled and labelled. Works with type(bar) and type(line) charts that
include over(). Example: sparkta price mpg, type(line) over(foreign) y2(mpg).

y2title(string) Label for the right y-axis.

y2range(min max) Explicit min and max for the right y-axis.

xtickcount(#) Approximate number of ticks on the x-axis.

ytickcount(#) Approximate number of ticks on the y-axis.

xtickangle(#) Rotation angle of x-axis tick labels in degrees.
Useful when category labels are long and overlap horizontally.

Example: sparkta price, over(rep78) xtickangle(45)

ytickangle(#) Rotation angle of y-axis tick labels in degrees.

xlabels(string) Custom tick labels for the x-axis, pipe-separated.
Applied left-to-right across the existing tick positions.

Example -- rename repair-record codes to plain English:

sparkta price, over(rep78) xlabels(Poor|Fair|Average|Good|Excellent)

ylabels(string) Custom tick labels for the y-axis, pipe-separated.

xstepsize(#) Interval between x-axis ticks. Example: xstepsize(500).

ystepsize(#) Interval between y-axis ticks.

xgridlines(on|off) Show or hide vertical grid lines. Default on.

ygridlines(on|off) Show or hide horizontal grid lines. Default on.

xborder(on|off) Show or hide the x-axis border line. Default on.

yborder(on|off) Show or hide the y-axis border line. Default on.

Chart behaviour

horizontal Render a bar chart with horizontal bars.
Equivalent to type(hbar).

stacked Stack multiple series on top of each other.
Applies to bar and area charts.

fill Fill the area between a line chart and the baseline.
Equivalent to type(area).

areaopacity(#) Fill opacity for type(area) and fill charts.
Accepts values from 0 (invisible) to 1 (fully opaque). Default is 0.35.
When multiple variables share an axis, lower values (0.3-0.5) keep
both fills visible. The y-axis is automatically anchored at zero for area charts.

Example: sparkta price weight, type(area) over(foreign) areaopacity(0.4)

smooth(#) Line smoothness (Bezier tension), 0 to 1.
smooth(0) produces sharp corners; smooth(0.6) produces flowing curves.
Default is 0.3.

Example: sparkta price, type(line) over(rep78) smooth(0.6)

spanmissing Connect lines across missing values instead of breaking.

stepped(string) Render lines as step functions.
Options: before | after | middle.
before steps up before reaching the x-value; after steps after;
middle centers the step at the midpoint between x-values.

Example: sparkta price, type(line) over(rep78) stepped(after)

Bar appearance

barwidth(#) Proportion of available width each bar occupies, 0 to 1.
Example: barwidth(0.6) for narrower bars.

bargroupwidth(#) Proportion of available width allocated to the group
of bars when multiple series are shown, 0 to 1.
Increasing this value narrows the gaps between groups.

Example: sparkta price weight, over(rep78) barwidth(0.8) bargroupwidth(0.7)

borderradius(#) Rounded corner radius of bars in pixels.
Values of 4-8 give a modern look without excessive rounding.

Example: sparkta price, over(rep78) borderradius(6)

opacity(#) Fill opacity of bars, 0 to 1. Default 0.85.

Points and lines

pointsize(#) Radius of point markers in pixels. Default 4.
Use pointsize(0) to hide markers.

pointstyle(string) Shape of point markers. Options:
circle (default) | cross | dash | line |
rect | rectRounded | star | triangle.

Example: sparkta price mpg, type(scatter) pointstyle(triangle) pointsize(6)

pointborderwidth(#) Border width of point markers in pixels. Default 1.

pointrotation(#) Rotation of point markers in degrees. Default 0.

linewidth(#) Width of lines in pixels. Default 2.

lpattern(string) Line dash pattern applied to all series on line and area charts.
Options: solid (default) | dash | dot | dashdot.
Example: lpattern(dash) draws all series as dashed lines.

lpatterns(string) Per-series line dash patterns, pipe-separated in series order.
Cycles if fewer patterns are supplied than series.
Accepted tokens: solid | dash | dot | dashdot.
Example: lpatterns(solid|dash|dot) gives the first series a solid line,
the second a dashed line, and the third a dotted line.
When both lpattern() and lpatterns() are specified, lpatterns()
takes precedence for each series it covers; remaining series fall back to lpattern().

nopoints Suppress point markers on line and area charts. When specified,
pointsize() and pointhoversize() have no effect. Equivalent to
pointsize(0) but also suppresses the hover highlight.

pointhoversize(#) Point radius in pixels when the cursor hovers over a data point.
Default is pointsize + 2. Ignored when nopoints is specified.

notesize(string) Font size for the note and caption text below the chart.
Accepts any valid CSS font-size value, for example notesize(1rem),
notesize(14px), or notesize(0.9em). When omitted, the theme defaults are used (.85rem for note, .78rem for caption).

Example: sparkta price, over(rep78) note(Source: 1978 auto data) notesize(0.8rem)

gradient Apply a vertical gradient fill to area and bar charts using
automatic palette-derived colors.
On area charts, the fill runs from the full series color at the top to
transparent at the bottom, creating a clean fade effect. On bar charts,
the gradient runs from the full color at the top to 60% opacity at the
bottom, adding subtle depth.

Example: sparkta price, type(area) over(rep78) gradient

gradcolors(c1|c2) Set custom start and end colors for the gradient,
separated by |. Any CSS color is accepted: hex codes, rgba(),
or named colors such as transparent. Examples:
gradcolors(#1e40af|transparent), gradcolors(rgba(251,146,60,1)|rgba(251,146,60,0)).
Specifying gradcolors() automatically enables the gradient fill without
needing to also specify gradient. gradient has no effect on line-only,
scatter, pie/donut, histogram, boxplot, or violin charts.

Example -- blue fade on an area chart:

sparkta price, type(area) over(rep78) gradcolors(#1e40af|transparent)

leglabels(list) Rename legend entries using a pipe-separated list, applied
in dataset order. Most useful when over() is specified, since over() creates
one dataset per group, each with its own legend entry. For example, if over(foreign)
produces groups 0 and 1, leglabels(Domestic|Foreign) replaces both default labels.
You may supply fewer labels than datasets; extra datasets keep their auto-generated names.
Not applicable to pie or donut charts (their legend labels come from data values, not dataset names).

Example -- foreign=0 is "Domestic", foreign=1 is "Foreign":

sparkta price, over(foreign) leglabels(Domestic|Foreign)

relabel(list) Rename over() group labels on both the x-axis tick
labels and the legend simultaneously, using a pipe-separated list in group order.
This mirrors Stata's over(var, relabel(1 "A" 2 "B")) with asyvars showyvars.

relabel() takes priority over leglabels() when both are supplied.
You may supply fewer labels than groups; extra groups keep their auto-generated names.

Behavior by chart type:

bar/hbar + over() x-axis and legend both renamed (colored swatches per group)

line/area + over() legend renamed (series names)

stackedbar + over() legend renamed (segment labels)

scatter/cibar/ciline legend renamed (group series)

boxplot/violin + over() x-axis renamed; inline legend shows chart-element symbols, not group names

pie/donut relabel() has no effect (slice labels come from data values)

Note for multi-variable charts: when multiple numeric variables are
combined with over(), relabel() renames the legend series entries
(variable dataset names) rather than the x-axis group tick labels.
This is a minor difference from Stata, where relabel() always targets
the over-group labels on the x-axis. In practice this combination is uncommon.

Example -- label rep78 groups in plain English:

sparkta price, over(rep78) relabel(Poor|Fair|Average|Good|Excellent)

Example -- with by() panels:

sparkta price, over(rep78) by(foreign) relabel(Poor|Fair|Average|Good|Excellent)

xticks(list) Pin x-axis tick positions to exact values.
Accepts a pipe-separated list of numbers. For example, xticks(0|25|50|75|100)
produces five evenly-spaced ticks on a 0-100 scale regardless of Chart.js auto-ranging.
Only meaningful on numeric (linear or logarithmic) x-axes; ignored on category axes.
Compatible with noticks: tick marks are still suppressed when both are specified,
but the tick label positions are controlled by this option.

yticks(list) Same as xticks() but for the y-axis.
Example: yticks(0|10000|20000|30000) for a salary chart.
All tokens must be valid numbers; non-numeric tokens produce an error.

Example -- show only round-thousand markers on the price axis:

sparkta price, over(rep78) yticks(0|5000|10000|15000)

Axis utilities

yreverse Reverse the direction of the y-axis so that values increase
downward rather than upward. Useful for rankings, depth scales, or any measure
where lower numeric values represent a "better" or "deeper" position.

Example -- rank chart where 1st place appears at top:

sparkta rank_var, over(group_var) yreverse ytitle(Rank)

xreverse Reverse the direction of the x-axis so that values decrease
left to right. Applies to numeric (linear) x-axes.

noticks Hide the short tick mark lines on both axes while keeping
tick labels visible. Produces a cleaner, more minimal look.
Compatible with xticks() and yticks().

ygrace(#) Add proportional whitespace above the y-axis maximum.
Accepts a fraction from 0 to 1: ygrace(0.1) extends the axis
ceiling by 10% of the data range, preventing the tallest bar or point
from touching the top of the plot area.

Example: sparkta price, over(rep78) datalabels ygrace(0.15) -- leaves room above the tallest bar so data labels are not clipped.

animduration(#) Set the animation duration in milliseconds directly.
Default is approximately 1000ms (Chart.js native default).
Overrides animate() when both are specified.
Use when animate(fast|normal|slow) does not give precise enough control.

Example: sparkta price, over(rep78) animduration(3000) -- 3-second animation regardless of animate() preset.

Layout and animation

aspect(#) Chart aspect ratio (width / height).
Values below 1 produce a taller chart; above 1 a wider chart.
Default is approximately 2 (wide landscape).

Example: sparkta price, over(rep78) aspect(1) -- square chart.

padding(#) Inner padding of the chart area in pixels.

animate(string) Animation speed. Options: fast | slow | none.
When omitted, Chart.js uses its native default (~1000ms).
fast = 150ms, slow = 1500ms, none = instant.
For precise control use animduration() instead.

easing(string) Animation easing function. Accepts any Chart.js
easing name -- this is a freeform string passed directly to Chart.js,
not validated by sparkta. Common values:
linear, easeInOutQuart (default),
easeOutBounce, easeInElastic, easeOutCirc.
Full list: Chart.js animation docs.

Example: sparkta price, over(rep78) animate(slow) easing(easeOutBounce)

animdelay(#) Delay before animation starts in milliseconds.

Tooltip

tooltipformat(string) Number format for tooltip values.
Accepts a d3-format string controlling decimal places and comma grouping.
The format is parsed for a decimal spec (.Nf) and comma (,).

,.0f comma thousands, 0 decimal places (e.g. 12,345)

,.2f comma thousands, 2 decimal places (e.g. 12,345.67)

.1f no comma, 1 decimal place (e.g. 12345.6)

.0f no comma, rounded integer (e.g. 12346)

When omitted, values are auto-formatted (0-4 dp, no trailing zeros,
comma thousands grouping).

Example: sparkta price, over(rep78) tooltipformat("$,.0f") -- displays values as $12,345.

tooltipmode(string) Tooltip interaction mode. Options: index
(default) | nearest | dataset | point | x | y.
index shows all series values at the hovered x-position simultaneously --
useful for comparing multiple lines at a glance.

Example: sparkta price weight, type(line) over(foreign) tooltipmode(index)

tooltipposition(string) Tooltip placement. Options: average
(default) | nearest.

tooltipbg(string) Background color of the tooltip box.
Accepts any CSS color: hex (#1a1a2e), named (navy), or
rgba() (rgba(0,0,0,0.9)). Default adapts to theme.

tooltipborder(string) Border color of the tooltip box.
Useful for matching a chart's accent color. Example: tooltipborder(#4e79a7).

tooltipfontsize(#) Font size of tooltip text in pixels.
Default is 13. Example: tooltipfontsize(14).

tooltippadding(#) Internal padding inside the tooltip box in pixels.
Default is 10. Example: tooltippadding(14).

Legend

legend(string) Legend position. Options: top (default) |
bottom | left | right | none (hides legend).

nolegend Suppress the legend entirely.
Equivalent to legend(none); provided as a convenient bare flag following
Stata convention (analogous to Stata's legend(off)).
Example: sparkta price weight, over(rep78) nolegend

legtitle(string) Title displayed at the top of the legend.

legsize(#) Font size of legend labels in pixels. Default 10.

legboxheight(#) Height of the legend color box in pixels.

legcolor(string) Text color of legend labels.
Example: legcolor(#ffffff) for white labels on a dark legend background.

legbgcolor(string) Background color of the legend panel.
Accepts any CSS color including rgba() for transparency.
Example: legbgcolor(rgba(255,255,255,0.85)).

Colors and styling

colors(string) Space-separated list of series colors (note: spaces, not pipes).
Accepts hex codes (e.g. #e74c3c #3498db), CSS color names, or
rgba(r,g,b,a) strings. Colors cycle if more series than colors provided.

Examples:

sparkta price weight, over(foreign) colors("#e74c3c #3498db") -- two hex colors

sparkta price weight, over(foreign) colors("red steelblue") -- named CSS colors

bgcolor(string) Page background color.

plotcolor(string) Chart plot area background color.

gridcolor(string) Color of grid lines.

gridopacity(#) Opacity of grid lines, 0 to 1. Default 0.15.

datalabels Show value labels on each bar or point.

pielabels Show value and percentage labels on pie/donut slices.

Font styling

titlesize(#) Font size of the main title in pixels. Example: titlesize(28).

titlecolor(string) Color of the main title text.
Example: titlecolor(#2c3e50).

subtitlesize(#) Font size of the subtitle in pixels.

subtitlecolor(string) Color of the subtitle text.

xtitlesize(#) Font size of the x-axis title in pixels.

xtitlecolor(string) Color of the x-axis title text.

ytitlesize(#) Font size of the y-axis title in pixels.

ytitlecolor(string) Color of the y-axis title text.

xlabsize(#) Font size of x-axis tick labels in pixels.

xlabcolor(string) Color of x-axis tick labels.

ylabsize(#) Font size of y-axis tick labels in pixels.

ylabcolor(string) Color of y-axis tick labels.

All styling options accept standard CSS colors: named (navy), hex
(#2c3e50), RGB (rgb(44,62,80)), or RGBA (rgba(44,62,80,0.9)).
Font size options accept positive integers (pixels). When these options are
omitted, the theme default is used.

PNG download and data handling

download Show a PNG download button in the top-right corner of the chart.
Clicking it saves the chart as a .png image file. Works in all modern browsers.

nomissing From v1.8.8, missing values in over(), by(),
filter(), filter2(), and varlist are automatically excluded
before chart building, matching Stata convention. Specifying nomissing
is therefore no longer required but is accepted for backward compatibility.

novaluelabels Display raw numeric codes instead of value labels
for over() and by() group names.
Useful when value labels are long or when you need to display the underlying codes.

Example: sparkta price, over(rep78) novaluelabels -- shows "1 2 3 4 5" instead of value label text.

Basic options

type(charttype) Chart type. Default is bar. All accepted values
are listed in Chart types above.

title(string) Main heading at the top of the chart page.
Defaults to Sparkta when omitted.

subtitle(string) Secondary heading displayed below the title.

note(string) Italic note displayed below the chart area.

caption(string) Small caption text below the note.

theme(string) Color theme and/or background. Bare background keywords:
default (white), dark (black), light (gray).
Named palettes: tab1, tab2, tab3, cblind1,
viridis, neon, swift_red.
Compound: dark_viridis, light_tab1, etc.
See Themes for the full list.

export(filepath) Save chart to a file instead of opening the browser.
Path must end in .html. Tilde ~ expansion works on all platforms.

Example: sparkta price, over(rep78) export("~/Desktop/prices.html")

offline Embed all JavaScript libraries inside the HTML file.
The result works with no internet connection (~280KB vs ~50KB default).
Required for institutional networks that block CDN requests.

sliders(varlist) Add dual-handle range sliders for one or more numeric
variables. The viewer drags the handles to restrict the plotted range
interactively. Accepts multiple space-separated variables:
sliders(mpg price). Only numeric variables are accepted.

horizontal Render bar chart with horizontal bars.
Identical to type(hbar). Provided as a convenient flag.

stacked Stack multiple series on top of each other. For bar charts:
series heights add up. For area charts: areas stack cumulatively.
Identical to type(stackedbar) or type(stackedarea).

fill Fill the area between a line chart and the x-axis baseline.
Identical to type(area).

gradient Apply a gradient fill to bars or area charts using the
current palette colors. Use gradcolors(start|end) to specify
exact start and end colors for all series.

fitci Add a 95% confidence interval band around the scatter fit line.
Supported for fit(lfit), fit(qfit), fit(exp),
fit(log), and fit(power). CI is computed in Stata before
the chart is built and recomputed when a slider changes.

datalabels Overlay the numeric value on each bar or pie slice.
Font size and color adapt automatically to the chart theme.

download Show a PNG download button in the top-right corner of
the chart. Clicking saves the current view as a .png image file.
Works in all modern browsers without any additional software.

pielabels Show percentage labels on pie and donut chart slices.
Labels appear inside each slice and show the rounded percentage share.

nostats Suppress the summary statistics panel below the chart.
Useful when sharing a compact chart where the stats are not needed.

nolegend Hide the chart legend entirely.
Equivalent to legend(none).

nopoints Hide point markers on line and area charts.
The line is still drawn; only the circular markers at each data point
are suppressed.

nomissing Exclude observations with missing values in over(),
by(), or filters() variables from all computations.
By default, missing values in grouping variables are already excluded;
this option makes the exclusion explicit and also applies to varlist.

novaluelabels Use raw numeric codes instead of Stata value labels
in chart groups and legends. By default, if rep78 has labels
1=Poor 2=Fair etc., those labels appear on the chart automatically.
Use this option to show 1 2 3 4 5 instead.

noticks Hide axis tick marks. The tick labels (numbers/categories)
remain visible; only the short lines extending from the axis are removed.

spanmissing Connect line segments across missing values in the
varlist variable. By default, a missing value creates a gap in the line.

yreverse Reverse the y-axis so larger values appear at the bottom.
Useful for rankings (rank 1 at top), depth measures, or any variable
where lower numbers represent a better or more prominent position.

Example: sparkta rank, over(country) type(hbar) yreverse

xreverse Reverse the x-axis so larger values appear on the left.

offline is documented above under Offline mode.

Examples

All examples use Stata's built-in auto dataset. Click any command
to run it directly.

Getting started

Load the data first:

sysuse auto, clear

Your first chart -- mean price by repair record:

sparkta price, over(rep78)

Add a title and an interactive filter dropdown:

sparkta price, over(rep78) title("Car Prices") filters(foreign)

CI bar chart with live filter and stats panel:

sparkta price, type(cibar) over(rep78) filters(foreign)

Scatter and fit lines

sparkta price mpg, type(scatter)

sparkta price mpg, type(scatter) fit(lowess) fitci

sparkta price mpg, type(scatter) fit(qfit) fitci sliders(mpg)

sparkta price mpg, type(scatter) over(foreign) fit(lfit)

Distributions

sparkta price, type(histogram)

sparkta price, type(boxplot) over(rep78)

sparkta price, type(violin) over(rep78) theme(dark_neon)

Panels

Separate chart panels by foreign, grouped by repair record within each:

sparkta price, over(rep78) by(foreign)

Arrange panels in a grid:

sparkta price, over(rep78) by(foreign) layout(grid)

Interactive filters and sliders

sparkta price, over(rep78) filters(foreign)

sparkta price, over(rep78) sliders(mpg)

sparkta price, type(cibar) over(rep78) filters(foreign) sliders(mpg)

Reference lines and annotations

sparkta price, over(rep78) yline(6000)

sparkta price, over(rep78) yline(4000|8000) ylinelabel(Low|High)

sparkta price, over(rep78) yband(4000 8000)

Themes and colors

sparkta price, over(rep78) theme(dark_viridis)

sparkta price, over(rep78) theme(cblind1)

sparkta price, over(rep78) colors(#e41a1c|#377eb8|#4daf4a|#984ea3|#ff7f00)

Offline mode

For institutional networks or air-gapped systems, bundle all JS inside the file:

sparkta price, over(rep78) offline export("chart_offline.html")

The resulting file is ~280KB and works with no internet connection.

Export to file

sparkta price, type(cibar) over(rep78) export("prices.html")

Summary statistics panel

Every chart includes a collapsible statistics panel showing N, mean, median,
min, max, SD, and CV per group, plus a sparkline of the distribution. The
panel updates automatically whenever a filter or slider changes.

Statistics match Stata's summarize command exactly: mean uses
sum/N, SD uses Bessel's correction (divides by N-1), median/Q1/Q3 use
Stata's exact interpolation formula.

Suppress with nostats. For large datasets, sparklines are rendered
lazily on scroll, keeping file sizes small.

Offline mode

By default, sparkta charts load Chart.js and related libraries from the
internet when the viewer opens them (~50KB download). Add offline
to bundle everything inside the HTML file (~280-320KB). Offline charts
work on air-gapped systems with no network requests of any kind.

Test with: sysuse auto, clear then
sparkta price, over(rep78) offline.

Stored results

sparkta stores nothing in e() or r(). It is a display
command that produces an HTML file as a side effect.

Common mistakes

Read these before experimenting -- they cover the six errors that trip up
almost every new sparkta user.

1. Scatter x/y reversed.
sparkta mpg price, type(scatter) puts mpg on the y-axis and price on x.
If you want price on y: sparkta price mpg, type(scatter).

Rule: y comes first, then x.

2. Pie chart without over().
sparkta price, type(pie) will error. Pie and donut always require
over() to know how to slice: sparkta price, type(pie) over(rep78).

3. histogram with over().
sparkta price, type(histogram) over(rep78) is not supported.
For separate histograms per group, use by():
sparkta price, type(histogram) by(foreign).

4. Combining over() and by() with pie or donut.
over() and by() work together for most chart types -- for example,
sparkta price, over(rep78) by(foreign) creates one panel per origin,
each showing grouped bars by repair record. The exception is pie and
donut: over() already defines the slices, so by() would just
repeat identical pies and is not permitted.

5. Forgetting that the default stat is mean.
sparkta price, over(rep78) shows mean price per group -- not sum or count.
Add stat(sum), stat(count), or stat(median) to change this.

6. Colors must use CSS format, not Stata format.
colors() accepts CSS color formats only: named colors (red, steelblue),
hex codes (#e74c3c), or rgba values (rgba(231,76,60,0.8)).
Stata color names like navy and maroon work for common colors --
but Stata-specific formats like gs8 or %50 do not.

Known limitations

Stata 17 or later is required. Running sparkta on Stata 16 or earlier
will produce an error before any chart is built.

Pie and donut charts require exactly one numeric variable and over().

Bubble charts require exactly three variables: y, x, and size (in that order).

over() and by() cannot be used together with pie or donut.
For all other chart types they can be combined: by() creates panels and
over() groups series within each panel.

histogram does not support over(). Use by() for separate
histograms per group.

cibar and ciline require over(). Groups with fewer than
2 observations are omitted from CI charts.

ytype(logarithmic) is incompatible with ystart(zero).

set java_heapmax requires a Stata restart to take effect.

Without the offline option, the HTML file requires an internet connection
to render (Chart.js loaded from CDN). Use offline for air-gapped use.

Memory and large datasets

sparkta reads observations directly from Stata memory and is not
limited by macro string length. Practical limits depend on available Java
heap memory. Default heap sizes and suggested fixes:

Stata version Default heap -- Suggested fix

Stata 15-16 384 MB --> set java_heapmax 1024m

Stata 17-18 512 MB --> set java_heapmax 1024m

Stata 19+ 4,096 MB --> Rarely needed; try set java_heapmax 8192m

Restart Stata after changing java_heapmax.
Check current heap with query java.
Approximate dataset size guide: up to ~100K observations is comfortable on
default settings; up to ~500K is achievable with the default Stata 19+ heap.

Statistical methods

All statistics match Stata's summarize output exactly.
Both the Java rendering layer and the JavaScript engine embedded in each
HTML file use identical formulas, so the statistics panel always matches
what you see in Stata.

N, Mean, SD, CV.
N is the count of non-missing observations. Mean is sum/N. SD uses
Bessel's correction (denominator N-1). CV is |SD/Mean|, guarded against
division by zero.

Median, Q1, Q3.
Stata's interpolation formula: position h = (n+1)*p/100. When h is
non-integer, the result is linearly interpolated between the floor(h) and
ceil(h) order statistics, clamped to [1, n]. Matches summarize, detail.

Confidence intervals (cibar, ciline).
Mean +/- t* x (SD/sqrt(N)), where t* uses the t-distribution with N-1
degrees of freedom at the level set by cilevel() (default 95%).
Groups with N < 2 are omitted. Matches Stata's ci means.
t-critical values: exact 8dp table for df 1-30; linear interpolation
df 31-120; Cornish-Fisher expansion df > 120 (max error < 1e-7).

Cornish, E.A. and Fisher, R.A. (1938).
Revue de l'Institut International de Statistique,
5, 307-320.

Histogram binning.
Sturges' rule: k = ceil(log2(n) + 1), clamped to [5, 50].
Override with bins(k).

Sturges, H.A. (1926). Journal of the American Statistical Association,
21(153), 65-66.

Violin kernel density.
Delegated to the chartjs-chart-boxplot plugin. Gaussian kernel with
Scott's rule: h = 1.06 x sigma x n^(-1/5). bandwidth() passes a
multiplier applied to the plugin's default.

Scott, D.W. (1992). Multivariate Density Estimation. Wiley, New York.

Box plot whiskers.
Most extreme observation within k x IQR of the box edges (IQR = Q3 - Q1).
Default k = 1.5 (Tukey fences). Override with whiskerfence(k).
Observations beyond the fences are drawn as outlier dots.

Tukey, J.W. (1977). Exploratory Data Analysis. Addison-Wesley.

Fit lines (fit()).
lfit, qfit: OLS.
exp (y=ae^bx), log (y=a+b*ln(x)), power (y=ax^b):
OLS after log linearisation. CI for exp/power is back-transformed from
the log scale (asymmetric bands wider above the fit line).
lowess: locally weighted regression, tricube weights, f=0.8,
matching Stata's lowess. ma: 5-point moving average.

Third-party plugins (all MIT licensed).

Chart.js 4.4.0 Core rendering engine

@sgratzl/chartjs-chart-boxplot 4.4.5 Box and violin charts

chartjs-chart-error-bars 4.4.0 CI error bars

chartjs-plugin-datalabels 2.2.0 Value label overlays

chartjs-plugin-annotation 3.0.1 Reference lines, bands, ellipses

Authors

Fahad Mirza

GitHub: github.com/fahad-mirza/sparkta_stata

Claude (Anthropic)

AI assistant and co-developer. Chart engine architecture, JavaScript filtering
engine, statistical methods implementation, Java/Stata integration, and
iterative debugging across all versions.
anthropic.com

Also see

Online: github.com/fahad-mirza/sparkta_stata

Install: //raw.githubusercontent.com/fahad-mirza/sparkta_stata/main/ado/") replace"':net install sparkta (click to reinstall)