Accessible SVG Chart Library for JavaScript – Britecharts

Category: Chart & Graph , Javascript , Recommended | December 1, 2026
Authorbritecharts
Last UpdateDecember 1, 2026
LicenseApache 2.0
Tags
Views0 views
Accessible SVG Chart Library for JavaScript – Britecharts

Britecharts is an open-source JavaScript library for creating interactive SVG charts with D3.js.

It includes bar, line, donut, heatmap, treemap, and other chart types with accessible data tables for screen readers.

Features

  • Arrow-key navigation and focus highlights on interactive charts.
  • Custom chart tooltips, legends, and a brush for selecting date ranges.
  • Negative values in bar charts and 100% stacked bar and area charts.
  • Built-in loading skeletons and optional animations that respect reduced-motion preferences.
  • SVG and PNG chart export.
  • Custom data palettes, category color maps, and CSS-based light and dark themes.
  • TypeScript definitions and JSON Schemas for chart configurations.
  • React components and wrappers for other JavaScript frameworks.

How To Use It

Installation

Load the stylesheet and JavaScript in the document.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@britecharts/[email protected]/dist/styles/bundle/britecharts.min.css">
<script src="https://cdn.jsdelivr.net/npm/@britecharts/[email protected]/dist/cdn/bundle/core.cdn.min.js"></script>

Or install and import them via NPM:

npm install @britecharts/core
import { bar, line, tooltip, colors } from '@britecharts/core';
import '@britecharts/core/dist/styles/bundle/britecharts.min.css';

Basic Usage

Add a container for the bar chart and place the script after it.

<div id="visits-chart"></div>
<script>
  const visits = [
    { name: 'Organic', value: 420 },
    { name: 'Direct', value: 260 },
    { name: 'Referral', value: 95 }
  ];
  const visitsChart = core.bar()
    .width(640)
    .height(280)
    .margin({ left: 90, right: 45 })
    .isHorizontal(true)
    .hasLabels(true)
    .labelsNumberFormat(',.0f')
    .colorSchema(core.colors.colorSchemas.okabeIto)
    .a11yTitle('Visits by traffic source')
    .tooltip(core.tooltip().numberFormat(',.0f'));
  visitsChart.render('#visits-chart', visits);
</script>

Create a Multi-Series Line Chart

Wrap the series rows in an object with a data property. Each row requires a numeric series ID (name), display name (topicName), ISO date (date), and value.

<div id="trend-chart"></div>
<script>
  const trendData = {
    data: [
      { name: 1, topicName: 'Organic', date: '2026-10-01T00:00:00Z', value: 210 },
      { name: 1, topicName: 'Organic', date: '2026-11-01T00:00:00Z', value: 420 },
      { name: 2, topicName: 'Direct', date: '2026-10-01T00:00:00Z', value: 180 },
      { name: 2, topicName: 'Direct', date: '2026-11-01T00:00:00Z', value: 260 }
    ]
  };
  const trendChart = core.line()
    .width(640)
    .height(320)
    .xAxisFormat(core.constants.axisTimeCombinations.CUSTOM)
    .xAxisCustomFormat('%b %d')
    .xTicks(4)
    .colorSchema(core.colors.colorSchemas.okabeIto)
    .a11yTitle('Monthly visits by source')
    .shouldShowAllDataPoints(true)
    .tooltip(core.tooltip().title('Visits').numberFormat(',.0f'));
  trendChart.render('#trend-chart', trendData);
</script>

Update, Resize, and Export Charts

Update Data and Loading State

Reuse the chart instance when the data changes.

const updatedVisits = [
  { name: 'Organic', value: 510 },
  { name: 'Direct', value: 310 },
  { name: 'Referral', value: 120 }
];
visitsChart.render('#visits-chart', updatedVisits);

Display a loading skeleton with isLoading(true) and an empty array while fetching bar chart data.

visitsChart.isLoading(true).render('#visits-chart', []);
// After receiving the new data:
visitsChart.isLoading(false).render('#visits-chart', updatedVisits);

Resize Charts

The SVG scales down to fit its container. Use a ResizeObserver to recalculate the layout at the new width.

const container = document.querySelector('#visits-chart');
let previousWidth = 0;
const observer = new ResizeObserver(([entry]) => {
  const width = Math.floor(entry.contentRect.width);
  if (width > 0 && width !== previousWidth) {
    previousWidth = width;
    visitsChart.width(width).render(container);
  }
});
observer.observe(container);

Export Charts

Call exportChart() from a download button or another user action.

// SVG
visitsChart.exportChart('visits.svg', 'Visits by source');
// PNG
visitsChart.exportChart('visits.png');

Render a Chart from a JSON Spec

Create chart.json. The $schema URL enables configuration validation in compatible editors.

{
  "$schema": "https://britecharts.github.io/britecharts/schema/v3/bar.json",
  "chart": "bar",
  "config": {
    "height": 280,
    "isHorizontal": true,
    "margin": { "left": 90, "right": 45 },
    "a11yTitle": "Visits by source"
  },
  "data": [
    { "name": "Organic", "value": 420 },
    { "name": "Direct", "value": 260 }
  ]
}

Install the wrapper and render the JSON configuration in your chart container. Define callback functions in JavaScript.

npm install @britecharts/wrappers
<div id="spec-chart"></div>
import { BarWrapper } from '@britecharts/wrappers';
import spec from './chart.json';
import '@britecharts/core/dist/styles/bundle/britecharts.min.css';
const element = document.querySelector('#spec-chart');
const chart = BarWrapper.create(element, spec.data, spec.config);

Chart Types and Data Formats

FactoryData format and purpose
bar()[{ name: 'Organic', value: 420 }]
One value per category.
groupedBar()[{ name: 'Nov', group: 'Organic', value: 420 }]
Bars sit side by side by group.
stackedBar()[{ name: 'Nov', stack: 'Organic', value: 420 }]
Series stack within a category.
line(){ data: [{ name: 1, topicName: 'Organic', date: '2026-11-01T00:00:00Z', value: 420 }] }
Time series; name is the numeric series ID.
stackedArea()[{ date: '2026-11-01T00:00:00Z', name: 'Organic', value: 420 }]
Stacked series by date.
donut()[{ name: 'Organic', quantity: 420, id: 1 }]
Shares of a total; id and percentage are optional. Include id for legend highlighting.
scatterPlot()[{ name: 'Organic', x: 10, y: 420 }]
Numeric coordinates; name identifies the series.
heatmap()[{ day: 0, hour: 9, value: 42 }]
Intensity by day (0 to 6) and hour (0 to 23); custom axis labels can represent other categories.
treemap()[{ name: 'Organic', value: 420 }]
Rectangles sized by value. Nonpositive values remain in the data table but occupy no area.
sparkline()[{ date: '2026-11-01T00:00:00Z', value: 420 }]
Compact time-series trend with no axes. Add a visible metric label in your HTML.
bullet(){ ranges: [200, 400, 600], measures: [420], markers: [500] }
One metric; bands and measures are arrays of up to three values. Markers are optional. Add a visible metric label in your HTML.
brush()[{ date: '2026-11-01T00:00:00Z', value: 420 }]
Date-window selection; null values represent gaps.
legend()[{ id: 1, name: 'Organic', quantity: 420 }]
Color key for a chart; quantity is optional.

Configuration and API Reference

Shared Chart Settings

AccessorArgument and behavior
widthNumber (pixels). SVG layout width.
Charts: All chart types and Legend.
Defaults: 960 (Bar, Grouped bar, Stacked bar, Line, Stacked area, Scatter plot, Bullet, Brush); 300 (Donut); 780 (Heatmap, Treemap); 100 (Sparkline); 320 (Legend).
heightNumber (pixels). SVG layout height.
Charts: All chart types and Legend.
Defaults: 500 (Bar, Grouped bar, Stacked bar, Line, Stacked area, Scatter plot, Brush); 300 (Donut); 270 (Heatmap); 400 (Treemap); 30 (Sparkline); 150 (Bullet); 180 (Legend).
marginObject. Top, right, bottom, and left margins in pixels. Partial objects are accepted. Defaults below are in top/right/bottom/left order.
Charts: All chart types and Legend.
Defaults: [20, 20, 30, 40] (Bar); [40, 30, 60, 70] (Grouped bar, Stacked bar); [60, 30, 40, 70] (Line); [70, 30, 60, 70] (Stacked area); [0, 0, 0, 0] (Donut, Treemap); [20, 10, 20, 40] (Scatter plot); [40, 20, 20, 40] (Heatmap); [5, 5, 5, 5] (Sparkline, Legend); [20, 20, 30, 20] (Bullet, Brush).
a11yTitleString or null. Accessible name; null uses the chart type.
Charts: All chart types and Legend.
Default: null.
a11yDescriptionString or null. Longer accessible description.
Charts: All chart types and Legend.
Default: null.
a11yDataTableBoolean. Renders a visually hidden accessible table after the SVG.
Charts: All data charts.
Default: true.
a11yKeyboardNavigationBoolean. Enables data-point navigation via arrow keys, Home, End, and Escape.
Charts: All data charts except Sparkline, Bullet, and Brush.
Default: true.
isLoadingBoolean. Shows the chart loading state.
Charts: All data charts.
Default: false.
isAnimatedBoolean. Enables drawing animations; reduced-motion preferences override this setting.
Charts: All data charts except Bullet.
Default: false.
animationDurationNumber (milliseconds). Length of the draw animation.
Charts: All data charts except Bullet.
Defaults: 1200 (All data charts except Scatter plot and Bullet); 600 (Scatter plot).
colorSchemaArray of color strings. Palette for chart data.
Charts: All chart types and Legend except Sparkline and Brush.
Defaults: ["#7bdcc0"] (Bar); Britecharts palette (Grouped bar, Stacked bar, Line, Stacked area, Donut, Scatter plot, Treemap, Bullet, Legend); red sequential palette (Heatmap).
colorMapObject or null. Maps category IDs or names to colors; Line keys use series IDs, grouped bars use group, and stacked bars use stack.
Charts: Bar, Grouped bar, Stacked bar, Line, Stacked area, Donut, Scatter plot, Legend.
Default: null.
numberFormatD3 number format string. Line, Stacked area, and Donut use automatic formatting when null.
Charts: Bar, Grouped bar, Stacked bar, Line, Stacked area, Donut, Bullet, Legend.
Defaults: ",f" (Bar, Grouped bar, Stacked bar); null (Line, Stacked area, Donut); "" (Bullet); "~s" (Legend).
valueLocaleObject or null. D3 number locale with decimal, thousands, grouping, and currency fields; optional numerals, percent, minus, and nan fields.
Charts: Bar, Grouped bar, Stacked bar, Scatter plot, Treemap.
Default: null.
tooltipTooltip instance or null. Attaches the tooltip with automatic event and field wiring; null detaches it. Use a fresh tooltip for each chart.
Charts: Bar, Grouped bar, Stacked bar, Line, Stacked area, Scatter plot, Heatmap, Treemap.
Default: null.

Axes, Formats, Orientation, and Labels

AccessorArgument and behavior
xAxisLabelString. X-axis title.
Charts: Bar, Line, Scatter plot.
Default: null.
yAxisLabelString. Y-axis title.
Charts: Bar, Grouped bar, Stacked bar, Line, Stacked area, Scatter plot.
Default: null.
xAxisLabelOffsetNumber (pixels). X-axis title offset.
Charts: Bar, Scatter plot.
Defaults: 30 (Bar); -50 (Scatter plot).
yAxisLabelOffsetNumber (pixels). Y-axis title offset.
Charts: Bar, Grouped bar, Stacked bar, Stacked area, Scatter plot.
Defaults: -30 (Bar); -60 (Grouped bar, Stacked bar, Stacked area); -50 (Scatter plot).
xTicksNumber. Requested X-axis tick count; for Line, Stacked area, and Brush, select the custom time format first. D3 determines the final tick count.
Charts: Bar, Grouped bar, Stacked bar, Line, Stacked area, Scatter plot, Brush.
Defaults: 5 (Bar, Grouped bar, Stacked bar); null (Line, Stacked area, Brush); 6 (Scatter plot).
yTicksNumber. Requested Y-axis tick count.
Charts: Bar, Grouped bar, Stacked bar, Line, Stacked area, Scatter plot.
Defaults: 5 (Bar, Grouped bar, Stacked bar, Line, Stacked area); null (Scatter plot).
gridString or null. Grid mode: vertical, horizontal, full, or null for the default.
Charts: Grouped bar, Stacked bar, Line, Stacked area, Scatter plot.
Default: null.
localeBCP 47 language tag or null. Locale for dates, such as en-US.
Charts: Line, Stacked area, Brush.
Default: null.
xAxisFormatString. For Line, Stacked area, and Brush, set minute-hour, hour-daymonth, day-month, month-year, custom, or null for automatic formatting. Scatter plot accepts a D3 number or time format string.
Charts: Line, Stacked area, Scatter plot, Brush.
Defaults: null (Line, Stacked area, Brush); "" (Scatter plot).
xAxisCustomFormatString. D3 date format used when xAxisFormat is custom.
Charts: Line, Stacked area, Brush.
Default: null.
xAxisValueTypeString. date or number; in number mode, supply numeric X values in the date field.
Charts: Line, Stacked area.
Default: "date".
xAxisScaleString. linear or logarithmic; applies to numeric X axes. Supply positive X values for a logarithmic scale.
Charts: Line, Stacked area.
Default: "linear".
tooltipThresholdNumber (pixels). Minimum chart width for tooltips. Lower the threshold to show tooltips on narrower charts.
Charts: Grouped bar, Stacked bar, Line, Stacked area.
Default: 480.
hasPercentageBoolean. Formats the value axis as percentages.
Charts: Bar, Stacked bar.
Default: false.
percentageAxisToMaxRatioNumber. Extends the percentage axis relative to the largest value.
Charts: Bar, Stacked bar.
Default: 1.
isHorizontalBoolean. Switches orientation to horizontal (for Legend, arranges entries horizontally).
Charts: Bar, Grouped bar, Stacked bar, Legend.
Default: false.
hasLabelsBoolean. Displays bar-end labels or treemap cell labels where they fit.
Charts: Bar, Treemap.
Defaults: false (Bar); true (Treemap).
labelsNumberFormatString. D3 number format for data labels.
Charts: Bar, Treemap.
Defaults: ",f" (Bar); "," (Treemap).

Bar, Grouped Bar, and Stacked Bar

AccessorArgument and behavior
betweenBarsPaddingNumber. Padding between bars.
Charts: Bar, Grouped bar, Stacked bar.
Default: 0.1.
betweenGroupsPaddingNumber. Padding between groups.
Charts: Grouped bar.
Default: 0.1.
chartGradientArray of two color strings or null. Color gradient for bars.
Charts: Bar.
Default: null.
hasSingleBarHighlightBoolean. True darkens the hovered bar; false darkens the other bars by default.
Charts: Bar.
Default: true.
highlightBarFunctionFunction or null. Custom highlighting callback receives a D3 selection; null disables highlighting.
Charts: Bar.
Default: built-in function.
labelsMarginNumber (pixels). Space from the end of the bar to its label.
Charts: Bar.
Default: 7.
labelsSizeNumber (pixels). Label text size.
Charts: Bar.
Default: 12.
orderingFunctionComparator function. Sorts bars or donut slices; donut slices default to descending quantity.
Charts: Bar, Donut.
Defaults: unset (Bar); built-in function (Donut).
shouldReverseColorListBoolean. Reverses the color list.
Charts: Bar.
Default: true.
yAxisPaddingBetweenChartNumber (pixels). Space between the Y axis and plot.
Charts: Bar.
Default: 10.
yTickTextOffsetObject { x, y }. Position offsets for Y-axis tick text.
Charts: Grouped bar.
Default: {"y": -8, "x": -20}.
hasReversedStacksBoolean. Reverses stack order.
Charts: Stacked bar.
Default: false.
isNormalizedBoolean. Normalizes each stack or time point to 100%; use nonnegative values.
Charts: Stacked bar, Stacked area.
Default: false.

Line and Stacked Area

AccessorArgument and behavior
hasMinimumValueScaleBoolean. Starts the Y scale at the dataset minimum.
Charts: Line.
Default: false.
linesArray of { y, name, color } objects. Adds horizontal reference lines with labels.
Charts: Line.
Default: [].
lineCurveString. Interpolation: linear, basis, natural, monotoneX, monotoneY, step, stepAfter, stepBefore, cardinal, or catmullRom.
Charts: Line.
Default: "linear".
lineGradientArray of two color strings. Line gradient (Line uses it for a single series).
Charts: Line, Sparkline.
Default: greenBlue gradient.
shouldShowAllDataPointsBoolean. Displays markers at all data points.
Charts: Line.
Default: false.
yAxisLabelPaddingNumber (pixels). Padding for the Y-axis title.
Charts: Line.
Default: 36.
areaCurveString. Interpolation curve: basis, monotoneX, monotoneY, natural, linear, step, stepAfter, stepBefore, cardinal, or catmullRom.
Charts: Stacked area, Brush.
Default: "monotoneX".
areaOpacityNumber. Opacity of stacked areas.
Charts: Stacked area.
Default: 0.24.
emptyDataConfigObject. Donut accepts showEmptySlice and emptySliceColor; Stacked area accepts minDate, maxDate, minY, maxY to define empty axes.
Charts: Stacked area, Donut.
Defaults: past month; y: 0 to 500 (Stacked area); {"emptySliceColor": "var(--bc-skeleton, #eff2f5)", "showEmptySlice": false} (Donut).
hasOutlineBoolean. Draws outlines at the top of stacked areas.
Charts: Stacked area.
Default: true.
topicsOrderArray of series names. Overrides the order of stacked area topics.
Charts: Stacked area.
Default: unset.
yAxisBaselineNumber. Y-value at the bottom of the area.
Charts: Stacked area.
Default: 0.

Donut and Scatter Plot

AccessorArgument and behavior
centeredTextFunctionFunction. Receives slice data (id, name, quantity, percentage) and returns center text; the default shows percentage and name.
Charts: Donut.
Default: built-in function.
externalRadiusNumber (pixels). Outer donut radius.
Charts: Donut.
Default: 140.
internalRadiusNumber (pixels). Inner donut radius.
Charts: Donut.
Default: 45.5.
hasCenterLegendBoolean. Shows center text in the donut.
Charts: Donut.
Default: true.
hasHoverAnimationBoolean. Enables the slice hover effect.
Charts: Donut.
Default: true.
hasFixedHighlightedSliceBoolean. Keeps the slice selected by highlightSliceById highlighted.
Charts: Donut.
Default: false.
hasLastHoverSliceHighlightedBoolean. Keeps the last hovered slice highlighted after mouseout; takes precedence over hasFixedHighlightedSlice.
Charts: Donut.
Default: false.
highlightSliceByIdNumber. ID of the slice to highlight.
Charts: Donut.
Default: unset.
percentageFormatString. D3 number format for the percentage label.
Charts: Donut.
Default: ".1f".
radiusHoverOffsetNumber (pixels). Radius expansion on hover.
Charts: Donut.
Default: 12.
circleStrokeOpacityNumber. Outline opacity of scatter points.
Charts: Scatter plot.
Default: 1.
circleStrokeWidthNumber (pixels). Outline width of scatter points.
Charts: Scatter plot.
Default: 1.
circleOpacityNumber. Fill opacity of scatter points.
Charts: Scatter plot.
Default: 0.24.
hasCrossHairsBoolean. Displays crosshair guides and axis values for the focused point.
Charts: Scatter plot.
Default: false.
hasHollowCirclesBoolean. Draws hollow markers.
Charts: Scatter plot.
Default: false.
hasTrendlineBoolean. Draws a linear regression trendline.
Charts: Scatter plot.
Default: false.
enableZoomBoolean. Enables zoom interactions.
Charts: Scatter plot.
Default: false.
highlightTextLegendOffsetNumber (pixels). Offset of crosshair value labels.
Charts: Scatter plot.
Default: -45.
maxCircleAreaNumber (pixels). Maximum circle radius; marker area represents the magnitude of the Y value.
Charts: Scatter plot.
Default: 10.
xAxisFormatTypeString. number selects number formatting; other values select time formatting.
Charts: Scatter plot.
Default: "number".
yAxisFormatString. D3 number format for Y values.
Charts: Scatter plot.
Default: "".

Heatmap, Sparkline, Bullet, Brush, and Legend

AccessorArgument and behavior
boxSizeNumber (pixels). Heatmap cell size.
Charts: Heatmap.
Default: 30.
xAxisLabelsArray of strings. Hour or column labels; unset uses hour labels (00h through 23h).
Charts: Heatmap.
Default: unset.
yAxisLabelsArray of strings. Day or row labels; unset uses Mo through Su.
Charts: Heatmap.
Default: unset.
areaGradientArray of two color strings. Sparkline area gradient.
Charts: Sparkline.
Default: theme sparkline gradient.
isReverseBoolean. Reverses bullet elements.
Charts: Bullet.
Default: false.
paddingBetweenAxisAndChartNumber (pixels). Space between the axis and bullet chart.
Charts: Bullet.
Default: 5.
startMaxRangeOpacityNumber. Starting opacity for the bullet range bands.
Charts: Bullet.
Default: 0.5.
ticksNumber. Requested X-axis tick count.
Charts: Bullet.
Default: 6.
dateRangeArray of two ISO date strings or nulls. Sets the selected brush window. Dragging updates it; clearing resets both ends to null.
Charts: Brush.
Default: [null, null].
gradientArray of two color strings. Brush area gradient.
Charts: Brush.
Default: greenBlue gradient.
isLockedBoolean. Keeps the selected window length fixed; initialize dateRange first.
Charts: Brush.
Default: false.
roundingTimeIntervalString. D3 time interval name used to round selection boundaries.
Charts: Brush.
Default: "timeDay".
highlightEntryByIdNumber. Legend entry ID to highlight on render.
Charts: Legend.
Default: null.
marginRatioNumber. Spacing multiplier for legend entries.
Charts: Legend.
Default: 1.5.
markerSizeNumber (pixels). Size of the legend color markers.
Charts: Legend.
Default: 16.
unitString. Unit appended to legend values.
Charts: Legend.
Default: "".

Time Format Constants

Use core.constants.axisTimeCombinations or the axisTimeCombinations property on Line, Stacked area, Brush, and Tooltip instances: MINUTE_HOUR, HOUR_DAY, DAY_MONTH, MONTH_YEAR, CUSTOM.

Methods and Events

MethodPurpose
render(target, data?)All chart factories and Legend. Target is a CSS selector, DOM element, or D3 selection. A selector uses its first match. Omit data after the initial render to redraw the last dataset for that container. Returns the chart.
on(eventName, callback?)Interactive charts listed below. Registers a callback and returns the chart; omit callback to read a registered handler or pass null to remove it. Supports D3 event namespaces.
exportChart(filename, title?)All data charts except Brush. Downloads SVG for a .svg filename and PNG otherwise; returns a Promise.
highlight(entryId)Legend. Highlights an entry by fading the other entries. Returns void.
clearHighlight()Legend. Clears the highlighted entries. Returns void.

Add a brush below the line chart to filter its series by the selected dates. Clearing the selection restores the full dataset.

<div id="date-filter"></div>
<script>
  const dateBrush = core.brush()
    .width(640)
    .height(100)
    .xAxisFormat(core.constants.axisTimeCombinations.CUSTOM)
    .xAxisCustomFormat('%b %d')
    .xTicks(4)
    .roundingTimeInterval('timeDay')
    .on('customBrushEnd', ([start, end]) => {
      const data = start && end
        ? trendData.data.filter(({ date }) => {
            const time = new Date(date);
            return time >= start && time <= end;
          })
        : trendData.data;
      trendChart.render('#trend-chart', { data });
    });
  dateBrush.render('#date-filter', [
    { date: '2026-10-01T00:00:00Z', value: 390 },
    { date: '2026-11-01T00:00:00Z', value: 680 }
  ]);
</script>
ChartsEvents
Bar, Donut, Heatmap, TreemapcustomMouseOver, customMouseMove, customMouseOut, customClick. Each handler receives the datum, [x, y] position, and [width, height]. Donut uses the arc datum; its slice record is under data.
Grouped bar, Stacked barcustomMouseOver, customMouseMove, customMouseOut, customClick. Hover and leave receive the datum and pointer position; movement receives the grouped datum, position, chart size, and color map. Click receives grouped data, pointer position, and the clicked bar or stack segment.
Scatter plotcustomMouseOver, customMouseMove, customMouseOut, customClick. Each receives the point datum and position; movement and click also receive the chart size.
Line, Stacked areacustomMouseOver, customMouseMove, customMouseOut, customDataEntryClick, customTouchMove. Hover, leave, entry click, and touch movement receive the datum and pointer position. Movement receives the series data point, position, chart size, and color map.
BrushcustomBrushStart and customBrushEnd. Both receive one array of two Dates; end dates are rounded to the selected interval. Clearing the brush returns two nulls.

Tooltip API

The tooltip() factory can draw a list of series values for multi-series charts or one value for a bar, heatmap, scatter plot, or treemap. The donut chart has center text for slice details and can be paired with a legend.

AccessorArgument, behavior, and default
dateFormatString. Date format mode: minute-hour, hour-daymonth, day-month, month-year, or custom. Default: "day-month".
dateCustomFormatString or null. Custom D3 date format used in custom mode. Default: null.
dateLabelString. Field for the title date; falls back to key or date. Default: "date".
localeBCP 47 language tag or null. Date locale. Default: null.
nameLabelString. Field holding the name or series ID used for a color lookup. Default: "name".
numberFormatString or null. D3 value format; null uses the automatic format. Default: null.
valueFormatterFunction or null. Custom value formatting function; overrides numberFormat. Default: null.
shouldShowDateInTitleBoolean. Includes the date in the title. Default: true.
titleString. Text heading. Default: "".
tooltipOffsetObject { x, y }. Anchor offset in pixels. Default: {"x": 0, "y": 0}.
layoutString. auto detects the data shape; list displays series rows; single displays a headline value. Default: "auto".
maxEntriesNumber. Maximum list rows; 0 shows every row. Default: 12.
topicsOrderArray of series names or IDs. Overrides row order. Default: [].
topicLabelString. Data field containing the rows. Default: "topics".
valueLabelString. Field containing the numeric value. Default: "value".
xAxisValueTypeString. auto, date, number, or category controls X-value formatting. Default: "auto".
MethodPurpose
show(dataPoint?, position?)Shows the tooltip, optionally rendering the data point at the supplied [x, y] position.
hide()Hides the tooltip.
update(dataPoint, position, chartSize?, colorMap?)Updates the displayed values and anchor; position and optional chartSize are [x, y] and [width, height]. colorMap is the series-to-color object.

To attach a tooltip through D3 events, connect customMouseOver to show, customMouseMove to update, and customMouseOut to hide. Mount the tooltip with selection.datum([]).call(tip) on .metadata-group .vertical-marker-container for Line and Stacked area or .metadata-group for the remaining charts in the table. Configure the data fields for each chart.

ChartTooltip field settings
Line, Bar, Heatmap, TreemapDefault fields.
Stacked areatopicLabel('values')
Stacked bartopicLabel('values').nameLabel('stack')
Grouped bartopicLabel('values').nameLabel('group')
Scatter plotvalueLabel('y'); optionally nameLabel('x') to show X as the name.

Styling and Customization

The built-in color palettes are available under core.colors.colorSchemas: britecharts, grey, orange, blueGreen, teal, green, yellow, pink, purple, red, okabeIto.

Use core.colors.colorGradients for greenBlue, orangePink, bluePurple, and core.colors.singleColors for aloeGreen, greenColor, blueColor, yellowColor, orangeColor, pinkColor, purpleColor. The corresponding colorSchemasHuman, colorGradientsHuman, and singleColorsHuman objects contain display names.

Set color-scheme: light dark to follow the system theme or color-scheme: dark to force dark mode. Override the CSS variables on .britechart after loading the stylesheet.

:root {
  color-scheme: light dark;
}
.britechart,
.britechart .tick text {
  font-family: system-ui, sans-serif;
}
@supports (color: light-dark(white, black)) {
  .britechart {
    --bc-text-muted: light-dark(#525252, #c8c8c8);
    --bc-background: light-dark(#ffffff, #171717);
  }
}
CSS custom propertyControls
--bc-textPrimary text.
--bc-text-mutedTick and data labels, tooltip titles.
--bc-text-subtleAxis titles.
--bc-axisAxis and tick lines, annotation lines.
--bc-gridGrid lines.
--bc-grid-highlightHighlighted grid line.
--bc-backgroundChart backdrop and export background.
--bc-surfaceTooltip surface, point markers, hollow circles, heatmap borders.
--bc-borderTooltip border and hover marker.
--bc-skeletonLoading skeleton color.
--bc-skeleton-strongStronger loading skeleton color.
--bc-brush-areaBrush area.
--bc-brush-area-missingGaps in the brush area.
--bc-sparkline-area-startStart of sparkline area gradient.
--bc-sparkline-area-endEnd of sparkline area gradient.

Use Britecharts in React

Install the React package in a project with React and React DOM.

npm install @britecharts/react

This component displays a responsive bar chart with a tooltip and a button for updating the data.

import { useState } from 'react';
import { Bar, ResponsiveContainer, Tooltip } from '@britecharts/react';
import '@britecharts/core/dist/styles/bundle/britecharts.min.css';
export default function VisitsChart() {
  const [data, setData] = useState([
    { name: 'Organic', value: 420 },
    { name: 'Direct', value: 260 }
  ]);
  return (
    <>
      <button onClick={() => setData(rows =>
        rows.map(row => ({ ...row, value: row.value + 10 }))
      )}>
        Update visits
      </button>
      <ResponsiveContainer render={({ width }) => (
        <Tooltip
          data={data}
          numberFormat=",.0f"
          render={props => (
            <Bar
              {...props}
              width={width}
              height={240}
              margin={{ left: 90, right: 45 }}
              isHorizontal
              hasLabels
              labelsNumberFormat=",.0f"
              a11yTitle="Visits by source"
            />
          )}
        />
      )} />
    </>
  );
}

React Components and Props

React componentFramework wrapper
BarBarWrapper
GroupedBarGroupedBarWrapper
StackedBarStackedBarWrapper
LineLineWrapper
StackedAreaStackedAreaWrapper
DonutDonutWrapper
ScatterPlotScatterPlotWrapper
HeatmapHeatmapWrapper
TreemapTreemapWrapper
SparklineSparklineWrapper
BulletBulletWrapper
BrushBrushWrapper
LegendLegendWrapper
TooltipTooltipWrapper

Pass the chart settings from the API reference as props, such as height={280}, margin={{ left: 90 }}, and isHorizontal={true}. The component-specific differences:

Prop or helperBehavior
dataRequired. Supplies the chart data. Pass a new array or object when data changes. Use null before the first dataset arrives or data={[]} with isLoading for an initial bar chart skeleton. Empty updates retain the displayed data. The Line component takes { data: [...] }; Bullet takes an array containing a single bullet data object.
exportChartFilename. Passing a different filename downloads another SVG or PNG. Supported by all data chart components except Brush.
highlight / clearHighlightLegend commands. Pass an entry ID to highlight, or clearHighlight={true} to clear the highlighted entry.
numberFormatAvailable on Bar, GroupedBar, Line, Donut, Bullet, and Legend. The Tooltip component has its own number format.
ResponsiveContainerAccepts a render={({ width }) => ...} function that receives the measured container width, including after window resizing.
withResponsiveness(Component)Returns a component that supplies the measured width prop. An explicit width overrides the measured width. Other props pass through.
axisTimeCombinationsImport these time format constants from @britecharts/react for the xAxisFormat prop.
TooltipWraps a chart with a data prop and a render function. Use the tooltip settings described below.

Use withResponsiveness() to define a reusable responsive chart component.

import { Bar, withResponsiveness } from '@britecharts/react';
const ResponsiveBar = withResponsiveness(Bar);
export function SalesChart({ data }) {
  return <ResponsiveBar data={data} height={240} />;
}

React Chart Events

Pass event callbacks as component props. They receive the chart event arguments defined in the Methods and Events reference.

ComponentsEvent props
Bar, GroupedBar, StackedBar, Line, StackedAreacustomMouseOver, customMouseMove, customMouseOut
Donut, ScatterPlot, Heatmap, TreemapcustomMouseOver, customMouseMove, customMouseOut, customClick
BrushcustomBrushStart and customBrushEnd receive [start, end] as one argument.
Bullet, Sparkline, LegendUse their data and configuration props to control the display.

React Tooltips

Pass data and a render callback to Tooltip. Spread the callback props onto the chart to pass its data and tooltip event handlers. The Tooltip component accepts the accessors in the Tooltip API reference as props and uses topicLabel="values" by default.

ChartTooltip props
Bar, Heatmap, Treemap, StackedAreaDefault field mappings.
LinetopicLabel="topics"
GroupedBarnameLabel="group"
StackedBarnameLabel="stack"
ScatterPlotvalueLabel="y"; optionally nameLabel="x".
DonutUse hasCenterLegend, centeredTextFunction, and a Legend component for slice details.

The tooltip accepts customMouseOver(), customMouseOut(), and customMouseMove(dataPoint, position, size, topicColorMap) callbacks. Pointer events control its visibility and position. Its command props show and update take a tooltip data point, and hide is a boolean trigger.

Use Britecharts in Vue, Svelte, and Other Frameworks

Use @britecharts/wrappers to integrate charts with component mount, update, and cleanup hooks.

Wrapper configuration and methods

The config object accepts the corresponding chart’s accessor names and values, such as { width: 640, height: 280, isHorizontal: true }. Supply event handlers as function-valued configuration keys.

MethodPurpose
create(element, data, config?)Creates the chart in a mounted element and returns the chart instance. The data uses the factory formats above; BulletWrapper takes an array containing one bullet object.
update(element, data, config, chart)Applies configuration changes, updates the data, and returns the chart instance. Pass null for data to redraw the current dataset with new settings. Empty arrays and empty line data objects also retain the current dataset.
destroy(element)Removes the chart SVG and its associated accessible data table. Call this during component cleanup.

To attach a tooltip to a chart with the tooltip accessor, import tooltip from @britecharts/core and call chart.tooltip(tooltip()) on the chart instance. Set exportChart to a filename to download the rendered chart. On LegendWrapper, set highlight to an entry ID or clearHighlight to true.

Configuration values of null or undefined leave the current setting unchanged. Pass false, 0, or an empty string to apply those values.

WrappersEvent keys
Bar, GroupedBar, StackedBar, Donut, ScatterPlot, Heatmap, Treemap wrapperscustomMouseOver, customMouseMove, customMouseOut, customClick
LineWrapper, StackedAreaWrappercustomMouseOver, customMouseMove, customMouseOut
BrushWrappercustomBrushStart and customBrushEnd

TooltipWrapper

The tooltip wrapper creates a tooltip in the SVG metadata group. It uses the tooltip configuration options above, with topicLabel set to "values" by default. Use "topics" for Line charts and the field mappings in the React Tooltips table for other supported charts.

MethodPurpose
TooltipWrapper.create(group, config?)Creates a tooltip in the metadata group and returns its instance. Use the vertical marker container for Line and Stacked area charts.
TooltipWrapper.update(group, config, state, tip)Updates the tooltip configuration, visibility, content, and position. State fields: isActive (boolean), x and y (pixel coordinates), dataPoint (current chart datum), and topicColorMap (series-to-color object). Returns the tooltip.
TooltipWrapper.destroy(element)Removes the tooltip from the supplied chart container.

Vue Example

Create a chart in onMounted, watch the data, and remove the chart in onBeforeUnmount.

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue';
import { BarWrapper } from '@britecharts/wrappers';
import '@britecharts/core/dist/styles/bundle/britecharts.min.css';
const host = ref(null);
const data = ref([
  { name: 'Organic', value: 420 },
  { name: 'Direct', value: 260 }
]);
let chart;
onMounted(() => {
  chart = BarWrapper.create(host.value, data.value, {
    width: 480, height: 240, isHorizontal: true,
    margin: { left: 90, right: 45 },
    hasLabels: true, labelsNumberFormat: ',.0f',
    a11yTitle: 'Visits by source'
  });
});
watch(data, rows => {
  if (chart) chart = BarWrapper.update(host.value, rows, {}, chart);
});
onBeforeUnmount(() => BarWrapper.destroy(host.value));
function update() {
  data.value = data.value.map(row => ({ ...row, value: row.value + 10 }));
}
</script>
<template>
  <button @click="update">Update visits</button>
  <div ref="host"></div>
</template>

Svelte Example

Use onMount to create the chart and return its cleanup function. The button updates the existing chart.

<script>
  import { onMount } from 'svelte';
  import { BarWrapper } from '@britecharts/wrappers';
  import '@britecharts/core/dist/styles/bundle/britecharts.min.css';
  let host;
  let chart;
  let data = [
    { name: 'Organic', value: 420 },
    { name: 'Direct', value: 260 }
  ];
  onMount(() => {
    chart = BarWrapper.create(host, data, {
      width: 480, height: 240, isHorizontal: true,
      margin: { left: 90, right: 45 },
      hasLabels: true, labelsNumberFormat: ',.0f',
      a11yTitle: 'Visits by source'
    });
    return () => BarWrapper.destroy(host);
  });
  function update() {
    data = data.map(row => ({ ...row, value: row.value + 10 }));
    chart = BarWrapper.update(host, data, {}, chart);
  }
</script>
<button onclick={update}>Update visits</button>
<div bind:this={host}></div>

Alternatives and Related Resources

You Might Be Interested In:


Leave a Reply