@internetstiftelsen/charts
v0.14.0
Published
A framework-agnostic, composable charting library built on D3.js with TypeScript.
Readme
Chart Library
A framework-agnostic, composable charting library built on D3.js with TypeScript.
Features
- Framework Agnostic - Works with vanilla JS, React, Vue, Svelte, or any framework
- Composable Architecture - Build charts by composing components
- Multiple Chart Types - XYChart (lines, scatter, areas, bars), WordCloudChart, DonutChart, PieChart, and GaugeChart
- Combined Chart Layouts -
ChartGroupcomposes existing charts into shared dashboards with one coordinated legend - Divergent Bar Support - Bar charts automatically render from zero and diverge around
0for mixed positive/negative values - Mirrored Bar Sides - Horizontal bars can mirror a series to the left for population-pyramid style charts without changing source data
- Custom Value Labels - XY, pie, donut, and gauge charts support configurable labels with formatters, max-width overflow behavior, and forced rendering when labels would otherwise be hidden
- Optional XY Animation - Animate XY series on first render and
chart.update(...)withanimate - Optional Radial Animation - Animate pie and donut segments on first render and
chart.update(...)withanimate - Optional Gauge Animation - Animate gauge value transitions with
gauge.animate - Stacking Control - Bar and area stacking modes with optional reversed visual series order
- Configurable Tooltips - Shared or split tooltips with connectors, transitions, and default max-width wrapping
- Axis Direction Control - Use
scales.x.reverse/scales.y.reverseto flip an axis when needed - Flexible Scales - Band, linear, time, and logarithmic scales (bar value axes stay linear)
- Explicit or Responsive Sizing - Set top-level
width/heightor let the container drive size - Auto Resize - Built-in ResizeObserver handles responsive behavior
- Responsive Policy - Chart-level container-query overrides for theme and components
- Lazy Mount Utility - Observe a container and defer chart imports until it approaches the viewport
- Type Safe - Written in TypeScript with full type definitions
- Data Validation - Built-in validation with helpful error messages
- Auto Colors - Smart color palette with sensible defaults
Installation
npm install @internetstiftelsen/chartsAgent Skill
This repo also ships a Codex-compatible skill in
skills/build-internetstiftelsen-charts.
Install it globally for Codex with skills.sh:
npx skills add [email protected]:internetstiftelsen/internal/webbgruppen/packages/charts.git \
-a codex \
-g \
--skill build-internetstiftelsen-chartsRestart Codex after installation so the new skill is discovered.
Local Development
pnpm devRuns the interactive demo app (index.html) with sidebar controls and
Chart/Data/Showcase tabs.
pnpm dev:docsRuns the marketing landing page (docs.html) built on
@internetstiftelsen/styleguide.
Build Targets
pnpm buildBuilds the publishable chart library output into dist.
pnpm build:docsBuilds the static marketing site into dist-docs (used for Pages deploys).
pnpm build:demoBuilds the demo app using the default Vite config.
Quick Start
import { XYChart } from '@internetstiftelsen/charts/xy-chart';
import { Line } from '@internetstiftelsen/charts/line';
import { XAxis } from '@internetstiftelsen/charts/x-axis';
import { YAxis } from '@internetstiftelsen/charts/y-axis';
const data = [
{ date: '2023', revenue: 100, expenses: 80 },
{ date: '2024', revenue: 150, expenses: 90 },
];
const chart = new XYChart({ data });
chart
.addChild(new XAxis({ dataKey: 'date' }))
.addChild(new YAxis())
.addChild(new Line({ dataKey: 'revenue' }))
.addChild(new Line({ dataKey: 'expenses' }));
chart.render('#chart-container');Use top-level width and height for fixed-size charts, or omit them to size
from the render container.
Theme overrides are deep-partial, so nested overrides like
theme.axis.fontSize preserve the rest of the theme defaults.
XY Animation
Enable animate on XYChart when you want series marks to animate on the
first render and on later chart.update(...) calls.
const chart = new XYChart({
data,
animate: {
duration: 700,
easing: 'ease-in-out',
},
});
chart
.addChild(new XAxis({ dataKey: 'month' }))
.addChild(new YAxis())
.addChild(new Line({ dataKey: 'value' }));
chart.render('#chart-container');
await chart.whenReady();Animation is off by default, applies to XY series marks only, and visual
exports always render the final static state.
Preset easing values include linear, ease-in, ease-out, ease-in-out,
bounce-out, elastic-out, and spring-out.
Lifecycle Events
Charts expose on() and off() for lifecycle subscriptions.
chart.on('ready', (event) => {
console.log(event.reason);
});See Getting Started for the supported events and payloads.
Lazy Loading
Use mountChartWhenVisible when you want the page to wait until a chart is
near the viewport before importing chart code and rendering it.
import { mountChartWhenVisible } from '@internetstiftelsen/charts/lazy-mount';
const lazyChart = mountChartWhenVisible(
'#chart-container',
async (container) => {
const [{ XYChart }, { Line }, { XAxis }, { YAxis }] = await Promise.all([import('@internetstiftelsen/charts/xy-chart'), import('@internetstiftelsen/charts/line'), import('@internetstiftelsen/charts/x-axis'), import('@internetstiftelsen/charts/y-axis')]);
const chart = new XYChart({ data });
chart
.addChild(new XAxis({ dataKey: 'month' }))
.addChild(new YAxis())
.addChild(new Line({ dataKey: 'value' }));
chart.render(container);
return chart;
},
{
rootMargin: '240px 0px',
},
);
// Optional: preload manually before it scrolls into view
await lazyChart.load();The utility is intentionally small: it observes the container, calls your async
factory once, and gives you load() plus destroy() so higher-level DOM
conventions such as data-chart scanners can build on top of it.
Chart Groups
Use ChartGroup when you want to combine existing charts into one layout while
keeping each child chart fully functional.
import { ChartGroup } from '@internetstiftelsen/charts/chart-group';
import { XYChart } from '@internetstiftelsen/charts/xy-chart';
import { Line } from '@internetstiftelsen/charts/line';
import { Bar } from '@internetstiftelsen/charts/bar';
import { Legend } from '@internetstiftelsen/charts/legend';
import { Text } from '@internetstiftelsen/charts/text';
import { Title } from '@internetstiftelsen/charts/title';
const lineChart = new XYChart({ data: lineData });
lineChart.addChild(new Line({ dataKey: 'revenue' }));
const barChart = new XYChart({ data: barData });
barChart.addChild(new Bar({ dataKey: 'revenue' }));
const group = new ChartGroup({
cols: 2,
gap: 20,
height: 420,
syncY: true,
});
group
.addChild(new Title({ text: 'Revenue vs Expenses' }))
.addChild(
new Text({
text: 'Source: finance team',
position: 'bottom',
variant: 'caption',
align: 'left',
}),
)
.addChart(barChart)
.addChart(lineChart)
.addChild(new Legend());
group.render('#chart-group');Legend state now works even without mounting a Legend on each child chart, so
grouped charts can share one coordinated legend while preserving child tooltip,
axis, and responsive behavior. ChartGroup.height behaves like chart height:
set it for a fixed total group height, or omit it to size from the render
container. Set syncY: true when you want vertical XYChart children to share
the same Y domain so grid lines stay aligned while only one child renders a
visible Y axis.
ChartGroup also supports declarative responsive layout overrides. Group
breakpoints can change cols and gap, while addChart(..., options) can
override span, height, order, or hidden per child. Just like chart
responsive config, both minWidth and maxWidth are supported and all
matching breakpoints merge in declaration order:
const group = new ChartGroup({
cols: 3,
responsive: {
breakpoints: {
tablet: { maxWidth: 1023, cols: 2 },
mobile: { maxWidth: 640, cols: 1, gap: 16 },
},
},
});
group
.addChart(barChart, {
responsive: {
breakpoints: {
mobile: { maxWidth: 640, hidden: true },
},
},
})
.addChart(lineChart, {
span: 2,
responsive: {
breakpoints: {
mobile: { maxWidth: 640, span: 1, order: -1 },
},
},
});Divergent Bars
Bar charts always render from a zero baseline. When bar data contains both
positive and negative values, the bars automatically diverge around 0 in both
vertical and horizontal orientations.
import { XYChart } from '@internetstiftelsen/charts/xy-chart';
import { Bar } from '@internetstiftelsen/charts/bar';
import { XAxis } from '@internetstiftelsen/charts/x-axis';
import { YAxis } from '@internetstiftelsen/charts/y-axis';
const chart = new XYChart({
data: [
{ metric: 'Pricing', delta: -18 },
{ metric: 'Feature set', delta: 24 },
{ metric: 'Support', delta: 11 },
],
orientation: 'horizontal',
});
chart
.addChild(new XAxis({ dataKey: 'metric' }))
.addChild(new YAxis())
.addChild(new Bar({ dataKey: 'delta' }));Automatic numeric bar domains always include 0. If you configure an explicit
numeric domain or min/max for the bar value axis, that final domain must
still include 0.
Categorical y axes now preserve data order from top to bottom by default.
Use scales.x.reverse or scales.y.reverse when you want to intentionally flip
an axis direction.
Responsive overrides are declarative and merge all matching breakpoints in declaration order:
const chart = new XYChart({
data,
responsive: {
breakpoints: {
sm: {
maxWidth: 640,
theme: {
axis: {
fontSize: 11,
},
},
components: [
{
match: { type: 'xAxis' },
override: { display: false },
},
],
},
md: {
minWidth: 641,
maxWidth: 768,
theme: {
axis: {
fontSize: 12,
},
},
},
},
},
});Word Cloud
import { WordCloudChart } from '@internetstiftelsen/charts/word-cloud-chart';
const data = [
{ word: 'internet', count: 96 },
{ word: 'social', count: 82 },
{ word: 'news', count: 75 },
];
const chart = new WordCloudChart({
data,
wordCloud: {
minValue: 5,
minWordLength: 3,
minFontSize: 3,
maxFontSize: 20,
padding: 1,
spiral: 'archimedean',
},
});
chart.render('#word-cloud');minFontSize and maxFontSize are percentages of the smaller plot-area
dimension and define the relative size range passed into d3-cloud. The chart
expects flat { word, count } rows, aggregates duplicate words after trimming,
and maps theme typography and colors directly into the layout and rendered SVG.
Export
chart.export() supports svg, json, csv, xlsx, png, jpg, and pdf.
await chart.export('png', { download: true });
await chart.export('csv', { download: true, delimiter: ';' });
await chart.export('xlsx', { download: true, sheetName: 'Data' });
await chart.export('pdf', { download: true, pdfMargin: 16 });xlsx and pdf are lazy-loaded and require optional dependencies (xlsx and
jspdf) only when those formats are used.
Import
toChartData() converts tab-delimited string input into chart JSON data.
It auto-detects grouped and normal (flat) table layouts.
import { toChartData } from '@internetstiftelsen/charts/utils';
import { XYChart } from '@internetstiftelsen/charts/xy-chart';
const data = toChartData('\t\tDaily\tWeekly\nAll users\tSegment A\t85%\t92%\n\tSegment B\t84%\t91%', {
categoryKey: 'Category',
});
const chart = new XYChart({ data });
chart.render('#chart-container');The parser supports JSON-escaped string payloads and grouped carry-forward row structure (blank first column on continuation rows).
Supported input shapes:
- Plain tab-delimited strings
- JSON-escaped string payloads
Auto-detection behavior:
- Grouped rows when a carry-forward group structure is present
- Flat rows when no grouped continuation rows are detected
Grouped parsing rules:
- Header row starts with two structural columns (
group,category) before metrics - Continuation rows leave the first column blank to inherit the previous group
- Blank separator rows are ignored
Documentation
- Getting Started - Installation, Vanilla JS, React integration
- XYChart - Line, area, and bar charts API
- ChartGroup - Combined chart layouts with a shared legend
- WordCloudChart - Word frequency visualization API
- DonutChart - Donut/pie charts API
- PieChart - Pie chart API
- GaugeChart - Gauge chart API
- Components - Axes, Grid, Tooltip, Legend, Text, Title
- Theming - Colors, fonts, and styling
Browser Support
Modern browsers with ES6+ support. Uses D3.js v7.
License
MIT
