web / charts
My web apps are a Go backend, hml templates, one plain CSS file, and a small browser script with no npm and no package manager. I draw charts with the same stack. A Go builder computes the geometry, an hml view writes divs or an SVG, and CSS paints them. There is no JavaScript charting library and, for most charts, no JavaScript.
The builders, the views, and the CSS are one Go package, github.com/croaky/chart. Each of my apps imports it.
The charts still respond to the reader. A hover opens with no round trip to the server, and a crosshair lands on the nearest date. A checkbox redraws six plots. A reader learns a color once and reads it on every page. web / live regions covers a page that redraws itself when data changes.
How much machinery
I pick the least machinery that answers the question the chart is for.
- Categorical and static: divs and CSS, geometry in Go. A funnel, a bar per category.
- A continuous axis, static: an SVG rendered server-side, geometry in Go. A metric over time.
- Hover detail: a panel placed in Go and shown by CSS. A panel that reads every series at one date belongs here too, because the dates are known before the page is sent.
- Filter, drill, or narrow to a range: an ajax round trip that re-renders the plot on the server.
- Interaction that cannot wait for a round trip: panning a range too large to refetch, or a value that follows the cursor between two marks. A script that reads the same JSON the Go builder already emits.
- WebGL, above roughly ten thousand marks on screen.
My charts use the fourth option for data changes. A small script links crosshairs across charts and selects a time range before the next request.
Three layers in one package
The package ships three layers, and its tests keep them in agreement:
- Builders in Go, one for each chart:
NewLines,NewSparkline,NewSeriesBars,NewValueBars,NewGroupedBars,NewValueGroupedBars,NewStackedColumns,NewXYScatter,NewEventMarks, andNewHeatmap. Each returns a struct that a view reads. - Views in hml, embedded in the package.
chart.Partialrenders one by a name that starts withchart/. - One stylesheet,
chart.CSS.
The part of a chart that drifts between pages is the part around the plot: the tip, the legend, the axis labels, and the class names. Two pages with two shapes for them read as two apps. The package has one shape for each, and every app gets it.
A handler calls a builder and puts the result in its locals:
lines := chart.NewLines(chart.USD, []chart.Series{{
Label: "Revenue",
Class: chart.SeriesClass(0),
Points: points,
}}, chart.WithLocation(loc))
The page renders the view:
= render "chart/lines", data: lines
The app's partial writer passes each chart/ name to the package
(see go / html templates).
The app serves chart.CSS beside its own sheet. Its rules sit in
@layer components, and every class starts with chart- (see
web / css).
Geometry in Go
A percentage, a polygon point, and a panel's placement are data. I compute them in a function a test can call, and the view writes the result. The bar chart builder returns a struct:
type Bar struct {
Label string `json:"label"`
Class string `json:"class"`
Count int `json:"count"`
Value string `json:"value"`
Style hml.SafeCSS `json:"style"`
Tip Tip `json:"tip"`
}
type Bars struct {
HasChart bool `json:"has_chart"`
Bars []Bar `json:"bars"`
Ticks []string `json:"ticks"`
}
hml finds a field by its json tag, so the tags are snake case. The
view loops and writes attributes. It runs no arithmetic:
- if data.has_chart
.chart-bars
.chart-axis-y.chart-axis-y--even
- for tick in data.ticks
%span.chart-axis-y-tick
= tick
.chart-bars-plot
- for bar in data.bars
.chart-bars-col.chart-tip-host{ tabindex: "0" }
.chart-bars-track
.chart-bars-bar{ class: bar.class, style: bar.style }
%span.chart-bars-count
= bar.value
%span.chart-axis-x
= bar.label
= render "chart/tip", data: bar.tip
A unit test asserts on the percentages and the tick labels with no browser. A second test renders each view from its builder and asserts on the markup. A third fails on a class that a view writes and the sheet does not style, and on a rule whose class no view writes.
When a builder has nothing to draw, it sets HasChart to false, and
its view renders nothing.
An SVG's viewBox is a fixed coordinate space, such as 0 0 1000 300. CSS stretches the element to the card's width with
preserveAspectRatio="none". The geometry is ratios rather than
pixels. A filled polygon takes that stretch without distortion. A
stroked line needs vector-effect: non-scaling-stroke, or it draws
thicker where it runs vertically than where it runs across. A glyph
would distort, so axis labels and dates stay in HTML beside the SVG.
Position by date
A point on a time axis sits where its date is in the range rather than where it is in the slice. A year with two observations and a year with none look different, and a gap in reporting draws as a gap:
func TimeXs(ts []time.Time, width float64) []float64 {
xs := make([]float64, len(ts))
if len(ts) == 0 {
return xs
}
if len(ts) == 1 {
xs[0] = width / 2
return xs
}
first := ts[0]
span := ts[len(ts)-1].Sub(first).Seconds()
for i, t := range ts {
if span <= 0 {
xs[i] = width * float64(i) / float64(len(ts)-1)
continue
}
xs[i] = width * t.Sub(first).Seconds() / span
}
return xs
}
A series with one observation is a polyline of that point twice over. A round line cap draws a zero-length line as a dot.
Hover panels without JavaScript
The browser draws a title attribute half a second late, in an OS
font, never on touch, and never on keyboard focus. So a hover is an
element the handler renders and CSS shows.
The host is the mark's container rather than the mark, because a two-pixel line is a poor target. The host is focusable, so the panel opens on keyboard focus as well as on hover:
.chart-tip-host {
position: relative;
&:is(:hover, :focus-visible, :focus-within) {
z-index: var(--z-index--component);
> .chart-tip,
> .chart-col-line {
opacity: 1;
visibility: visible;
}
}
}
.chart-tip {
opacity: 0;
pointer-events: none;
position: absolute;
top: 100%;
transition: opacity 100ms ease 120ms, visibility 100ms ease 120ms;
visibility: hidden;
width: max-content;
max-width: min(20rem, 80vw);
}
I use visibility rather than display, so the panel can transition,
and it leaves the accessibility tree while hidden. The transition
waits 120 ms before it opens or closes a panel. So a pointer that
crosses two columns to reach a third does not flash a panel at each.
The mark lightens while its panel is open, so the two read as one
thing. There is no cursor: pointer on a mark that is not a link.
A panel near the left edge of a plot opens rightward. A panel near the right edge opens leftward. A panel in the middle centers on its mark. This is the part that usually needs a positioning library. The panel is a fixed width, and the handler knows the mark's position along the axis. So the handler picks the class:
func tipClassAt(pos float64) string {
switch {
case pos < 1.0/3.0:
return "chart-tip--left"
case pos > 2.0/3.0:
return "chart-tip--right"
default:
return "chart-tip--center"
}
}
The handler splits by thirds rather than by first and last, because a centered panel needs half its width of room on each side.
The panel is one type for every chart. It has a title, labeled facts one per line, and an optional list of names. The list stops at eight names and gives a count of the rest. The title is the mark's name in full, since the axis under it abbreviates.
Crosshair bands
A crosshair is a hover per date. The plot has one band per date, absolutely positioned over the SVG, and each band spans halfway to each neighbor:
func TimeColumns(xs []float64, width float64) []Column {
cols := make([]Column, 0, len(xs))
for i, x := range xs {
left, right := 0.0, width
if i > 0 {
left = (xs[i-1] + x) / 2
}
if i < len(xs)-1 {
right = (x + xs[i+1]) / 2
}
bandWidth := right - left
lineAt := 0.5
if bandWidth > 0 {
lineAt = (x - left) / bandWidth
}
cols = append(cols, Column{
Style: bandStyle(left/width, bandWidth/width),
LineStyle: atStyle(lineAt),
})
}
return cols
}
bandStyle writes --chart-left and --chart-width, and atStyle
writes --chart-at. The style attribute holds custom properties only,
and the sheet spends them.
The band is the hover host. Its panel lists every series with a value on that date. The line inside it sits at the date's own position, which is off the band's center when the neighbors are unevenly spaced. Two observations four years apart give two bands half the plot wide.
Every panel is in the HTML already. Two years of weekly points across ten series is a hundred panels of ten lines each. That is more markup than a script would need, but it is still smaller than a chart library and it works with JavaScript off.
Linked inspection
On a page of related time charts, I inspect one bucket across every plot.
The readout names each chart and prints its values at that bucket.
The axes, hover panels, and readout use one labelled timezone.
Each builder takes it as WithLocation, and WithClock12 prints
3:04 PM where a reader expects a 12-hour clock. TimeTicks reads the
same options, so a label the page prints itself matches the chart.
A date without a time is insufficient for a chart of minutes.
Go supplies the bucket start, step, and count in data attributes. A small browser script finds the bucket under the pointer. It moves the crosshairs and reads the facts already in the HTML. It fetches no data and computes no percentiles.
I map the pointer against the plot, excluding its axes and padding. A selected bucket retains its exact start and end. The first and last buckets need tests, including a partial last bucket. A bar's center and a line point can have different pixel positions. The shared bucket time, rather than one pixel offset, links the plots.
On phones, a tap shows the same readout. Each chart's facts occupy a separate line above the plots. The values have no small internal scroll box that competes with page scrolling.
Two palettes
I keep two palettes, because two questions have opposite answers.
An ordered category, such as a stage in a pipeline or a count in a heatmap cell, wants neighbors that look related, so a reader sees distance along the order. That is one ramp, cool at one end and warm at the other, with interpolated stops:
:root {
--color--ramp-1: #e3f2fd;
--color--ramp-2: #cbe7f8;
--color--ramp-3: #a7d1ee;
--color--ramp-4: #709ec5;
--color--ramp-5: #3b658d;
--color--ramp-6: #f6a89e;
--color--ramp-7: #ea796f;
--color--ramp-8: #cc4844;
}
The ramp does not use the brand palette. Brand colors stand apart from each other. A tag needs that separation, but a ramp needs the opposite.
Several things compared on one plot have no order, so neighbors have to look unrelated. That is a second palette of ten distinct hues, at a lightness that reads as a two-pixel line on white. Ten is the limit. An eleventh hue is one a reader has to look up in the legend every time.
Each class sets its color once, as a custom property. One rule applies it as the stroke of a line, the fill of a polygon, and the background of the legend swatch:
.chart-series {
background-color: var(--chart-mark);
fill: var(--chart-mark);
stroke: var(--chart-mark);
}
.chart-series--1 {
--chart-mark: var(--color--series-1, light-dark(#1e66f5, #8caaee));
}
.chart-series--2 {
--chart-mark: var(--color--series-2, light-dark(#fe640b, #ef9f76));
}
The app's tokens set the colors. The fallback in each var() lets the
sheet draw in an app that sets none.
The legend swatch uses the same class as its line, so a key cannot
drift from its series. The Go side is one lookup per palette:
SeriesClass(0) returns chart-series chart-series--1, and
RampClass(1) returns chart-ramp chart-ramp--1. The heatmap picks a
ramp step from a cell's share of the largest count. I write each class
out in full, so a search for the selector finds the code that sets it.
Some colors are data, such as a sports team's own color. A series then
sets Color to a hex value, and the views write it as --chart-mark
on the line, its end dot, its end label, and its legend swatch. The
builder drops a value that is not #rgb or #rrggbb, because the
value goes into a style attribute.
On a page of six plots, the handler assigns colors once from a list it has ordered. Each series brings its own class to the builder. The same thing is the same color in all six. The checkbox row that picks what to compare shows a dot per option in that option's line color, so the row is also the legend. The dot is round and the legend swatch is square: one is a control and the other is a key.
Axis steps and labels
The tallest bar stops at a number the axis labels, rather than at the top of the box. So a bar scales against the axis maximum rather than the largest value in the data.
For small integers, a fixed step table is enough: 2 up to 10, 5 up to
25, 10 up to 50. For anything larger, the step is the 1/2/5 sequence
at the range's own magnitude, the nice idea from d3:
func niceStep(raw float64) float64 {
mag := math.Pow(10, math.Floor(math.Log10(raw)))
switch norm := raw / mag; {
case norm <= 1:
return mag
case norm <= 2:
return 2 * mag
case norm <= 5:
return 5 * mag
default:
return 10 * mag
}
}
The target is about four gaps, because the plots are half a card wide. A count has no half of a thing to label, so its smallest step is 1.
The axis and the hover print numbers through one function,
FormatValue, in one Format: a count, dollars, a unit price, a
percent, milliseconds, or a signed count. A hover that says
1,150,000,000 next to an axis labeled 1B asks the reader to do the
conversion the chart is for.
A signed axis
NewValueAxis always holds zero. A bar or a line measured from an axis
that starts at 40 makes a change of 10% look like a change of 100%.
A range that crosses zero takes its step from its larger side, with about three gaps on that side. Both sides then read off one step, and the axis stays close to the data. A range from -6 to +6 steps by 2. A step from the full width would be 5, and the axis would run from -10 to +10.
A line chart whose axis runs below zero draws a zero rule under its lines. A linear axis that starts at zero has its zero on the bottom edge already.
WithDomain(lo, hi) fixes the axis when the data does not set the
scale. A probability runs from 0 to 100. On the ENSO board, each
anomaly runs from -6 to +6, so every plot reads on one scale.
The Signed format prints the sign of each value: +6, 0, and −6. The
minus is U+2212, the width of the plus, so the digits line up down the
axis.
Sparkline
NewSparkline draws the shape of a series and names its ends. It has
no hover and no style attribute. Its geometry is SVG attributes, and the
view prints the four labels in plain order around the SVG: the top and
the bottom of the value axis, and the first and the last date. CSS
places them with a grid.
It reads the same options as NewLines and computes the same plot. So
a sparkline and a line chart of one series have one shape.
End labels
WithEndLabels names each line at its right end, with its series and
its last value, in the line's color. A dot marks the last point. A
polyline of that point twice draws the dot, because a circle would
stretch into an ellipse with the SVG.
A label sits at the height of its line's last point. Two labels closer than a tenth of the plot's height move apart, and the larger value stays on top. Without that, two lines that end near each other print two labels on top of each other.
With end labels, NewLines leaves out the legend. Each line has its
name at its end, so a legend below the plot would name it a second
time.
One markup for two layouts
A categorical bar chart is columns on a wide screen and rows on a narrow one, label beside bar, from the same markup. The bar's share of the axis is a custom property, set inline by Go:
func pctStyle(share float64) hml.SafeCSS {
return hml.SafeCSS(fmt.Sprintf("--chart-pct: %.1f%%", 100*min(max(share, 0), 1)))
}
Columns spend it as a height. Rows spend it as a width:
.chart-bars-bar {
height: var(--chart-pct);
}
@media (width < 70em) {
.chart-bars:not(.chart-bars--long) {
.chart-bars-col {
flex-direction: row;
}
.chart-bars-bar {
height: auto;
width: var(--chart-pct);
}
}
}
Go sets a custom property rather than an inline height, because CSS
cannot reread an inline height as a width. The percentage in the
custom property works as either. So there is no breakpoint in Go, no
second partial, and no scroll container. A column has no min-width,
because the count of columns is data and the card is not always as
wide as the page.
Content-Security-Policy
A view with hover bands, bars, or placed labels writes style
attributes. Each attribute sets custom properties only, such as
--chart-pct and --chart-at. A policy of style-src 'self' makes
the browser drop those attributes, and the bars and bands lose their
places. So those views need style-src-attr 'unsafe-inline':
style-src 'self'; style-src-attr 'unsafe-inline'
That keeps <style> elements and style sheets to 'self', and it
keeps script-src as it is. A style attribute can run no script.
The sparkline is the one view that needs no exception. A series
Color is the one style attribute it can write, so under
style-src 'self' a series takes its color from its class. My
ENSO conditions board draws only
sparklines colored by class, so its policy keeps style-src 'self'
with no style-src-attr.
Marks as links
A reader who sees a tall stack in one quarter wants the rows behind
it. So in the stacked column plot, each segment is an <a> in place
of a <div>, with the same height style. Its URL is the page's
current URL plus a period parameter, such as period=2026Q2, and
the filter box that the segment stands for. The handler calls
WithLinkAttr("ajax-get") on the chart, so each link also carries
ajax-get with the same URL. A click then swaps the page body without
a full load. The package names no attribute of its own, so the page's
script decides what the hook is.
The handler narrows the table, the count, and the CSV export to that
period. It counts the chart's rows before the period narrows them. So
the chart still draws every period, and the reader still sees the
column they picked. The picked column keeps its color. The other
columns fade but stay links. A line over the table names the period
and links back to all periods. A period key for a column that the
chart does not draw is a stale link, so the table ignores it and shows
every period.
A second click on the picked column clears the pick. The handler builds one cleared URL with no period and with the chart's filter groups empty. It gives that URL to each segment of the picked column. The search and the other filters stay.
The pick lives in the URL, so it survives a reload, and a reader can send it to a teammate.
Filtering with a round trip
A row of checkboxes above a comparison page picks what to draw. A change submits the form over ajax, and the response replaces the plots:
%form{ "ajax-get": "/charts", "ajax-submit-on-change": "1" }
- for opt in data.compare_options
%label.chart-compare-option
%input{ type: "checkbox", name: "compare[]", value: opt.value, checked: opt.selected }
%span.chart-compare-dot{ class: opt.dot_class }
%span
= opt.label
The form sits outside the element the response replaces, so the box just ticked survives the swap. The response renders the same chart view the page rendered on load, from the same builder. The form submits with no debounce, because a click on a checkbox is a finished input. There is no copy of the selection in the browser to keep in step with the server.
Select a time range
On a performance page, I drag across a plot to select a time range.
The script maps the drag to whole buckets and shows the selection on every plot.
It writes the bucket edges as from and to in the URL.
The server filters the charts and route table with that same window.
The browser script handles pointer coordinates. Go keeps the data rules.
Links between metrics and logs carry those fixed times and the current filters.
A relative value such as range=1h would move the window between requests.
I keep the service identity in the path.
A route drilldown replaces the path filter and keeps the other terms.
The URL survives reload and supports browser back and forward. A reset link returns to the previous wider range, including an exact custom window. It does not always return to the page's default hour.
A horizontal drag selects, with a finger or a mouse. The plots set
touch-action: pan-y, so a vertical swipe still scrolls the page and
cancels the gesture. A tap inspects one bucket. A tap outside the
charts clears that inspection and leaves the chosen window alone.
Reset clears the window. There is no mode button and no help text.
The page also has labelled start and end fields for keyboard use. That
form submits the same from and to values without a script.
A bucketed series has one rule for the pointer: the bucket it is in. Each point stands for the span that starts at its time, so a hover panel covers that span instead of the half-way split to the nearest point. Without that, a pointer in the right half of a bucket shows the next bucket's values beside a readout that names the bucket under it.
One row holds the time controls. The range menu names a dragged window instead of the preset it came from, so it never says "30 minutes" over a custom span. Reset sits beside it, and the exact fields sit behind a summary.
A table sort is a link that swaps the table:
%a.perf-sort{ href: h.URL, "ajax-get": h.URL, "ajax-swap": ".perf-routes-wrap" }
The href is the page the link stands for, so a modified click or a
browser with no script loads it. The swap keeps the page and table
scroll, and each sort pushes its URL, so back and forward restore the
rows.
I test the data boundaries in Go and the gestures in a browser. Browser tests exercise real navigation between logs and metrics. They also cover reload, back and forward, and reset. Phone tests check vertical scrolling separately from range selection. I inspect the pixels as well as the URLs.
Why not a JavaScript library
Observable Plot sits on about thirty d3 modules, and my apps have no package manager to maintain them with. A chart in Go compiled to WebAssembly draws through a canvas shim. Canvas loses text selection, find-in-page, the CSS tokens, and printing.
Two ideas from Plot are worth writing in Go. One is the nice axis
above. The other is a scale as a function from domain to range. In the
package, TimeXs is one for time, and the linear and log axes are one
for values.
Fit
This fits a server-rendered application where the handler already owns
the data. It needs five platform features: a viewBox, :hover,
:focus-within, a custom property, and a form that submits on change.