# Britecharts documentation
Every guide and API page from https://britecharts.github.io/britecharts/, as text. The index is https://britecharts.github.io/britecharts/llms.txt.
---
# Britecharts
Source: https://britecharts.github.io/britecharts/docs/Britecharts
> Finished, accessible charts that any page, and any agent, can add with one script tag or one validated JSON config.
[](https://www.npmjs.com/package/@britecharts/core) [](https://opensource.org/licenses/Apache-2.0) [](https://github.com/britecharts/britecharts/actions/workflows/unit-tests.yml) [](https://github.com/britecharts/britecharts/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc) [](https://www.jsdelivr.com/package/npm/@britecharts/core)
[](https://github.com/britecharts/britecharts/blob/main/.github/CONTRIBUTING.md) [](https://britecharts.github.io/britecharts/docs/Britecharts#contributors-) [](https://twitter.com/Britecharts/followers)
| [![Bar Chart][barchartimg]][barchart-story] | [![Line Chart][linechartimg]][linechart-story] | [![Donut Chart][donutchartimg]][donutchart-story] |
| --- | --- | --- |
| [![Stacked Bar Chart][stackedbarchartimg]][stackedbarchart-story] | [![Stacked Area Chart][stackedareachartlargeimg]][stackedareachart-story] | [![Grouped Bar Chart][groupedbarchartimg]][groupedbarchart-story] |
| [![Sparkline Chart][sparklinechartimg]][sparklinechart-story] | [![Legend Chart][legendchartimg]][donutchart-story] | [![Brush Chart][brushchartimg]][brushchart-story] |
Britecharts is a library of finished [D3.js][d3] charts: bar, line, donut, stacked and grouped bar, stacked area, scatter plot, heatmap, treemap, sparkline, bullet and brush, plus a tooltip and a legend. You choose a chart, give it data and a few settings, and get a polished, interactive, accessible chart that works the same in plain HTML, any framework or React.
## Why Britecharts
### Finished charts, not a grammar
Grammar libraries hand you scales, marks and axes to assemble. Britecharts hands you a bar chart. Every chart shares one vocabulary (`width`, `colorSchema`, `isLoading`, `numberFormat`, `exportChart`, `a11yTitle`) and comes with loading and empty states, animation, tooltips and export already built. There are fewer ways to go wrong, for people and for coding agents alike.
### Accessible by default, and free
Every chart is accessible without any setup:
- 🔊 **Named for screen readers**, with its data as a table they can read cell by cell.
- ⌨️ **Keyboard navigable**: tab to a chart, move between data points with the arrow keys, and the tooltip follows focus.
- 🎞 **Still when the reader asks for reduced motion.**
- 🎨 **A colour-blind-safe palette**, Okabe–Ito, one setting away.
Commercial libraries charge per seat for this set. In Britecharts it is on by default, and each part can be turned off.
### One script tag or one config, in any page
The vanilla core runs anywhere: a server-rendered template, a static site, a Web Component, or an AI sandbox that only allows CDN scripts. The same chart is available as a framework-agnostic wrapper and as a React component. And because a chart is a name, a configuration and data, it can be written down as a JSON spec that a schema checks before it's drawn.
### Made for coding agents too
Agents write Britecharts correctly on the first try more often when the library helps them:
- 📄 **[llms.txt][llms-txt]** and **llms-full.txt** describe every chart and accessor.
- 🧠 **An agent skill** ships inside `@britecharts/core`, with each chart's data shape, accessors and common traps.
- ✅ **A JSON Schema for every chart's spec**, so an editor or an agent can validate a config without running it.
- 💬 **Errors that say how to fix them**: a misspelt key gets "did you mean `height`?" and a link to the chart's API page, and a value of the wrong type says what it should be.
### Charting since 2015
Britecharts started at Eventbrite in May 2015. Version 1 reached npm in March 2017, and version 2 followed that August. Since then, 55 people have contributed code and the repository has earned over 3,700 stars on GitHub. Version 2 is still installed about 5,000 times a week.
Version 3 keeps the idea that made those charts last: a chart is a function you configure and then call on your data. It rebuilds everything around it in TypeScript, with accessibility, theming, React components and tools for coding agents.
## What's New in Version 3
Version 3 is a rewrite of Britecharts in TypeScript, on D3 v7, as three packages: [`@britecharts/core`][core-package], [`@britecharts/wrappers`][wrappers-package] and [`@britecharts/react`][react-package].
- **Accessibility built in.** Named charts, [data tables and keyboard navigation][a11y-howto], reduced motion and the Okabe–Ito palette, all on by default.
- **[Theming and dark mode][theming-howto]** with standard CSS. Every colour around the data is a `--bc-*` custom property, and the charts follow the page's `color-scheme` through `light-dark()`.
- **[Export to SVG or PNG][export-howto]** from one call: `exportChart('chart.svg')`.
- **[Chart specs and JSON Schemas][spec-howto]**, generated from the TypeScript types, with value checks in the wrappers.
- **TypeScript types** for every chart's data, configuration and React props.
- **Every chart in every package**, the brush and heatmap included, and **one tooltip** for all of them.
- **Responsive by default**: every svg scales to fit its container, with no resize listeners.
- **Negative values** in the bar, grouped bar, stacked bar, brush and scatter plot charts, and **loading states** on every chart.
- **Smaller bundles**: ES modules that tree-shake, so an app only ships the charts it imports.
Coming from version 2? Read the [migration guide][migration-guide].
## Quick Start
### Try it in your browser
[Open a running example on StackBlitz][try-page], in plain JavaScript or React, with nothing to install. Each draws a bar chart and a line chart with their tooltips, switches to dark mode, and moves through the data with the keyboard.
### From a CDN, with no build step
```html
```
The bundle includes d3, so the page needs no other script.
### From npm
```bash
npm install @britecharts/core
```
```js
import { bar, tooltip } from '@britecharts/core';
import '@britecharts/core/dist/styles/bundle/britecharts.min.css';
bar()
.isHorizontal(true)
.height(300)
.a11yTitle('Signups by plan')
.tooltip(tooltip())
.render('.bar-container', data);
```
`render` takes a CSS selector, an element or a d3 selection, and draws again with new data when you call it again. If you already use d3, `select('.bar-container').datum(data).call(barChart)` works too.
### With React
```bash
npm install @britecharts/react
```
```jsx
import { Bar } from '@britecharts/react';
;
```
In an app set up with [shadcn/ui](https://ui.shadcn.com), one command adds a chart that follows your theme and its dark mode, with [one registry item per chart][shadcn-howto]:
```bash
npx shadcn@latest add https://britecharts.github.io/britecharts/r/bar-chart.json
```
To use Britecharts with another framework, use the `create`, `update` and `destroy` methods of the [wrappers package][wrappers-package]. For Angular, check out [ngx-britecharts][angularwrapper].
### As a JSON spec
```json
{
"$schema": "https://britecharts.github.io/britecharts/schema/v3/bar.json",
"chart": "bar",
"config": { "isHorizontal": true, "a11yTitle": "Signups by plan" },
"data": [{ "name": "Pro", "value": 412 }]
}
```
Editors validate and complete it from the schema, and `BarWrapper.create(element, spec.data, spec.config)` draws it.
## Charts
Every chart shares the common accessors (`width`, `height`, `margin`, `colorSchema`, `isLoading`, `a11yTitle` and so on) and adds its own:
- [API][line-docs], [Demo][linechart-story] Line Chart
- [API][bar-docs], [Demo][barchart-story] Bar Chart
- [API][donut-docs], [Demo][donutchart-story] Donut Chart
- [API][stacked-bar-docs], [Demo][stackedbarchart-story] Stacked Bar Chart
- [API][grouped-bar-docs], [Demo][groupedbarchart-story] Grouped Bar Chart
- [API][stacked-area-docs], [Demo][stackedareachart-story] Stacked Area Chart
- [API][scatter-docs], [Demo][scatterplot-story] Scatter Plot
- [API][heatmap-docs], [Demo][heatmap-story] Heatmap
- [API][treemap-docs], [Demo][treemap-story] Treemap
- [API][sparkline-docs], [Demo][sparklinechart-story] Sparkline Chart
- [API][bullet-docs], [Demo][bulletchart-story] Bullet Chart
- [API][brush-docs], [Demo][brushchart-story] Brush Chart
- [API][tooltip-docs], [Demo][linechart-story] Tooltip, and its [single-value preset][mini-tooltip-docs]
- [API][legend-docs], [Demo][donutchart-story] Legend
[line-docs]: https://britecharts.github.io/britecharts/docs/API/line
[bar-docs]: https://britecharts.github.io/britecharts/docs/API/bar
[donut-docs]: https://britecharts.github.io/britecharts/docs/API/donut
[stacked-bar-docs]: https://britecharts.github.io/britecharts/docs/API/stacked-bar
[grouped-bar-docs]: https://britecharts.github.io/britecharts/docs/API/grouped-bar
[bullet-docs]: https://britecharts.github.io/britecharts/docs/API/bullet
[brush-docs]: https://britecharts.github.io/britecharts/docs/API/brush
[scatter-docs]: https://britecharts.github.io/britecharts/docs/API/scatter-plot
[heatmap-docs]: https://britecharts.github.io/britecharts/docs/API/heatmap
[treemap-docs]: https://britecharts.github.io/britecharts/docs/API/treemap
[sparkline-docs]: https://britecharts.github.io/britecharts/docs/API/sparkline
[stacked-area-docs]: https://britecharts.github.io/britecharts/docs/API/stacked-area
[mini-tooltip-docs]: https://britecharts.github.io/britecharts/docs/API/tooltip#minitooltip-the-single-value-preset
[tooltip-docs]: https://britecharts.github.io/britecharts/docs/API/tooltip
[legend-docs]: https://britecharts.github.io/britecharts/docs/API/legend
Britecharts is built with the [reusable chart pattern][mike-chart] on plain D3.js code you can read, fork and modify, and every chart is covered by unit tests and by browser tests in real consumer apps. To customise the look, see [Styling Britecharts][stylingbritecharts].
## See Also
- [Documentation Homepage][docs-homepage]
- [Getting Started Guide][gettingstarted]
- [Tutorials][tutorialsindex]
- [How To Guides][howtoindex]
- [Topics][topicsindex]
- [Contributing Guide][contributing-guide]
- [Github Repo][main-repository]
- [Changelog][changelog]
## Community Roadmap
This project is in active development. We want your input about what is important, for that, add your votes using the 👍 reaction:
* [Top Feature Requests](https://github.com/britecharts/britecharts/issues?q=is%3Aissue+is%3Aclosed+sort%3Areactions-%2B1-desc+label%3Atype%3Afeature+-label:status:completed)
* [Documentation Requests](https://github.com/britecharts/britecharts/issues?q=is%3Aissue+is%3Aclosed+sort%3Areactions-%2B1-desc+label%3Atype%3Adocumentation+-label:status:completed)
* [Top Bugs](https://github.com/britecharts/britecharts/issues?q=is%3Aissue+is%3Aclosed+sort%3Areactions-%2B1-desc+label%3Atype%3Abug+-label:status:completed)
## How to Contribute
Whether you're helping us fix bugs, improving the docs, or spreading the word, we'd love to have you as part of the Britecharts community!
To give your feedback, you can open a new issue. You can also find us in the [D3.js slack group][d3slack], in the **#tool-britecharts** channel. We are looking for contributors and committers, so if you want to become a part of this project, check the [contributing guide][contributing-guide] for ideas on contributing and get started today!
## Code of Conduct
Britecharts is dedicated to building a welcoming, diverse, and safe community. We expect everyone participating in the Britecharts community to abide by our [Code of Conduct][code-conduct]. Please read it and follow it.
## Acknowledgments
[Sun Dai][sunsdribble] designs Britecharts, and two books inspired the code, [Developing a D3.js Edge][d3-edge] and [Mastering D3.js][mastering-d3]. It also leveraged a significant number of examples and articles from the [D3.js][d3] community overall.
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://github.com/all-contributors/all-contributors#emoji-key)):
This project follows the [all-contributors](https://allcontributors.org) specification. Contributions of any kind are welcome!
## License
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[https://www.apache.org/licenses/LICENSE-2.0][license-original]
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Read more in the [license document][britecharts-license]
[core-package]: https://britecharts.github.io/britecharts/docs/packages/core-readme
[wrappers-package]: https://britecharts.github.io/britecharts/docs/packages/wrappers-readme
[llms-txt]: https://britecharts.github.io/britecharts/llms.txt
[a11y-howto]: https://britecharts.github.io/britecharts/docs/how-tos/user-how-to-guides#how-to-make-a-chart-accessible
[theming-howto]: https://britecharts.github.io/britecharts/docs/how-tos/user-how-to-guides#how-to-theme-a-chart-and-support-dark-mode
[export-howto]: https://britecharts.github.io/britecharts/docs/how-tos/user-how-to-guides#how-to-export-a-chart
[spec-howto]: https://britecharts.github.io/britecharts/docs/how-tos/user-how-to-guides#how-to-describe-a-chart-as-a-spec-and-check-it
[shadcn-howto]: https://britecharts.github.io/britecharts/docs/how-tos/user-how-to-guides#how-to-add-a-chart-to-a-shadcn-app
[migration-guide]: https://britecharts.github.io/britecharts/docs/how-tos/migration-guide-2-to-3
[heatmap-story]: https://britecharts.github.io/britecharts/docs/API/heatmap 'Check the API reference'
[treemap-story]: https://britecharts.github.io/britecharts/docs/API/treemap 'Check the API reference'
[d3]: https://d3js.org/
[mike-chart]: https://bost.ocks.org/mike/chart/
[changelog]: https://github.com/britecharts/britecharts/blob/main/CHANGELOG.md
[license-original]: https://www.apache.org/licenses/LICENSE-2.0
[britecharts-license]: https://github.com/britecharts/britecharts/blob/main/LICENSE.md
[d3-edge]: https://www.goodreads.com/book/show/22252178-developing-a-d3-js-edge
[mastering-d3]: https://www.packtpub.com/web-development/mastering-d3js
[docs-homepage]: https://britecharts.github.io/britecharts/
[storybook]: https://britecharts.github.io/britecharts/docs/tutorials/tutorials-index
[main-repository]: https://github.com/britecharts/britecharts
[gettingstarted]: https://britecharts.github.io/britecharts/docs/tutorials/getting-started
[contributing-guide]: https://github.com/britecharts/britecharts/blob/main/.github/CONTRIBUTING.md
[d3-selection]: https://github.com/d3/d3-selection
[cdndemo]: https://britecharts.github.io/britecharts/docs/tutorials/installing-britecharts
[cdnhome]: https://www.jsdelivr.com/package/npm/britecharts
[jsbinsandbox]: https://jsbin.com/wativun/3/edit?html,js,output
[codepensandbox]: https://codepen.io/Golodhros/pen/PprGeP?editors=1010
[codependemos]: https://codepen.io/Britecharts/pens/forked/
[angularwrapper]: https://github.com/colapdev/ngx-britecharts
[angularwrapperdemos]: https://colapdev.github.io/ngx-britecharts/
[twitter]: https://twitter.com/britecharts
[sunsdribble]: https://dribbble.com/sundai
[d3slack]: https://d3js.slack.com/messages/tool-britecharts/
[proposals]: https://github.com/britecharts/britecharts/issues?q=is%3Aopen+label%3A%22Type%3A+Feature%22+sort%3Aupdated-desc
[release4project]: https://github.com/britecharts/britecharts/issues
[barchart-story]: https://britecharts.github.io/britecharts/docs/API/bar 'Check the API reference'
[linechart-story]: https://britecharts.github.io/britecharts/docs/API/line 'Check the API reference'
[donutchart-story]: https://britecharts.github.io/britecharts/docs/API/donut 'Check the API reference'
[scatterplot-story]: https://britecharts.github.io/britecharts/docs/API/scatter-plot 'Check the API reference'
[sparklinechart-story]: https://britecharts.github.io/britecharts/docs/API/sparkline 'Check the API reference'
[stackedareachart-story]: https://britecharts.github.io/britecharts/docs/API/stacked-area 'Check the API reference'
[brushchart-story]: https://britecharts.github.io/britecharts/docs/API/brush 'Check the API reference'
[bulletchart-story]: https://britecharts.github.io/britecharts/docs/API/bullet 'Check the API reference'
[stackedbarchart-story]: https://britecharts.github.io/britecharts/docs/API/stacked-bar 'Check the API reference'
[groupedbarchart-story]: https://britecharts.github.io/britecharts/docs/API/grouped-bar 'Check the API reference'
[stackedarea-story]: https://britecharts.github.io/britecharts-react/#stacked-area-chart 'Check the Demo'
[barchartimg]: https://britecharts.github.io/britecharts/img/thumbnails/bar-chart.png
[linechartimg]: https://britecharts.github.io/britecharts/img/thumbnails/line-chart.png
[donutchartimg]: https://britecharts.github.io/britecharts/img/thumbnails/donut-chart.png
[sparklinechartimg]: https://britecharts.github.io/britecharts/img/thumbnails/sparkline-chart.png
[stackedareachartlargeimg]: https://britecharts.github.io/britecharts/img/thumbnails/stacked-area-chart-large.png
[brushchartimg]: https://britecharts.github.io/britecharts/img/thumbnails/brush-chart.png
[stackedbarchartimg]: https://britecharts.github.io/britecharts/img/thumbnails/stacked-bar-chart.png
[groupedbarchartimg]: https://britecharts.github.io/britecharts/img/thumbnails/grouped-bar-chart.png
[legendchartimg]: https://britecharts.github.io/britecharts/img/thumbnails/legend-chart.png
[tutorialsindex]: https://britecharts.github.io/britecharts/docs/tutorials/tutorials-index
[howtoindex]: https://britecharts.github.io/britecharts/docs/how-tos/how-to-index
[topicsindex]: https://britecharts.github.io/britecharts/docs/topics/topics-index
[stylingbritecharts]: https://britecharts.github.io/britecharts/docs/tutorials/styling-charts
[code-conduct]: https://github.com/britecharts/britecharts/blob/main/CODE_OF_CONDUCT.md
[britecharts-react]: https://britecharts.github.io/britecharts-react/
[github-projects]: https://github.com/orgs/britecharts/projects
[react-package]: https://britecharts.github.io/britecharts/docs/packages/react-readme
[try-page]: https://britecharts.github.io/britecharts/try
---
# Getting Started Using Britecharts
Source: https://britecharts.github.io/britecharts/docs/tutorials/getting-started
We created Britecharts to help users consume and create D3.js charts. It leverages the *Reusable API*, a code pattern to encapsulate D3.js charts. This pattern produces chart objects that can be configured, reused and composed to build data visualizations.
In this tutorial, we will *create a simple data visualization using Britecharts*. You will learn how to load Britecharts, instantiate and configure a chart and plot it within a container with a data set.
## Downloading Britecharts
To use a Britechart, we need to install the library. In this tutorial, we are going to use a simple CDN link to install it. For that, create a simple HTML file and add this script tag:
```html
```
The bundle has every chart, and the d3 modules they use, so the page needs no other script.
We also need to load the styling of our chart, and we do it similarly by accesing the CDN link:
```html
```
## Setting up Container, Dataset and Chart
To create a container, we add a div in the DOM with a class:
```html
```
We instantiate a new chart by calling the function bar() inside the `core` object in the global namespace:
```js
const barChart = core.bar();
```
We need a simple dataset to render the bar chart. We can find the right format of the data by visiting the [API documentation][barChartAPI] for the bar chart component. Developers need to find the data definition at the top of the page; in this case, it is a link labeled [BarChartData][barChartDataSchema]. It looks like this:
```json
[
{
value: 1,
name: 'glittering'
},
{
value: 1,
name: 'luminous'
}
]
```
We can extend that definition to have some more bars, for example:
```js
const barData = [
{ name: 'Luminous', value: 2 },
{ name: 'Glittering', value: 5 },
{ name: 'Intense', value: 4 },
{ name: 'Radiant', value: 3 }
];
```
## Configuring and Rendering the bar chart
We only need to configure our bar chart by calling the accessors. We describe these in the [bar chart API reference][barChartAPI] page. In this tutorial, we set it up as a horizontal bar chart with a height of 400px and a width of 600px:
```js
barChart
.margin({left: 100})
.isHorizontal(true)
.height(400)
.width(600);
```
Notice how we tweaked a bit the left margin in order to allow space for our left aligned labels to render.
We only need to render our configured bar chart into the container, with the data:
```js
barChart.render('.bar-container', barData);
```
`render` takes a CSS selector, an element or a d3 selection. Calling it again with new data redraws the chart.
To render a simple bar chart:
![Simple Bar Chart][barChartImg]
Here is all the code inside the `` tag of our HTML file:
```html
```
In version 3 of Britecharts, the rendered charts are already responsive, so you can stretch and compress the viewport size to see the chart react.
You can check the full code of this tutorial [in this file][simpleBarChartTutorialHTML] and the [tutorial working here][simpleBarChartTutorial].
## Summary
In this tutorial, we have seen how to load Britecharts with a CDN link and how to draw a simple chart. We did this by checking the API Reference page for the chart and its data schema and by creating the elements needed in the HTML file.
To keep on learning more about Britecharts, you can follow our [Composing Your First Data Visualization tutorial][composingDataviz] or read abbout how to [install Britecharts in your project][installingBritecharts]. You can also check out our [Documentation Homepage][home] and our [kitchen sink][demos] to see all the available charts.
If you are excited about Britecharts, want to add more configurable properties or even create your own chart, please check our [Contributing Guide][contribute]. In it, we walk you through the development environment setup, running our docs and demos and creating new Pull Requests.
[home]: https://britecharts.github.io/britecharts/
[demos]: https://britecharts.github.io/britecharts/storybook/
[contribute]: https://github.com/britecharts/britecharts/blob/main/.github/CONTRIBUTING.md
[barChartAPI]: https://britecharts.github.io/britecharts/docs/API/bar
[barChartDataSchema]: https://britecharts.github.io/britecharts/docs/API/bar#exportsbarchartdata--arrayobject
[barChartImg]: https://raw.githubusercontent.com/britecharts/britecharts/main/packages/docs/static/img/tutorial/simple-bar-chart.png
[simpleBarChartTutorialHTML]: https://github.com/britecharts/britecharts/blob/main/packages/docs/docs/tutorials/html/tutorial-simple-bar-chart.html
[simpleBarChartTutorial]: https://britecharts.github.io/britecharts/storybook/core/?path=/story/charts-bar--playground
[composingDataviz]: https://britecharts.github.io/britecharts/docs/tutorials/composing-dataviz
[installingBritecharts]: https://britecharts.github.io/britecharts/docs/tutorials/installing-britecharts
---
# Installing Britecharts
Source: https://britecharts.github.io/britecharts/docs/tutorials/installing-britecharts
In the [Getting Started Guide][gettingStarted] you saw how to use Britecharts using a CDN link. This is not the only way. Britecharts allows developers to add the library following several strategies.
In this tutorial, you will learn to install Britecharts in your project by using different approaches:
* Using a package manager (npm or pnpm)
* Using the CDN links
* Building the Source Code
## Install with NPM
The recommended way of installing Britecharts is to use npm or pnpm:
```
npm install --save @britecharts/core
```
Or, using pnpm:
```
pnpm add @britecharts/core
```
Notice this requires you to have in place a bundling system (Webpack, Parcel, Rollup, or Similar). If you want to drop a script in an HTML file and start working, use the CDN way below.
To use the modules within your JavaScript code, you will follow a different approach depending on the type of modules you are using:
```js
// For CommonJS modules
const { bar } = require('@britecharts/core');
// For ES modules
import { bar } from '@britecharts/core';
bar().render('.bar-container', data);
```
The charts draw with `render`, so you don't need d3 in your own code. If you do use d3, `select('.bar-container').datum(data).call(barChart)` works too.
When loading the styles, you have two options, loading the whole stylesheet of the library:
```html
```
Or loading only the styles for the current chart plus the common Britecharts styles:
```html
```
## Download from the CDN
To import the latest bundle (3.x.x version), use this URL:
```
https://cdn.jsdelivr.net/npm/@britecharts/core/dist/cdn/bundle/core.cdn.min.js
```
This bundle attaches to the global `window` object a JavaScript object called `britecharts`. Within it, you can find the charts and helpers you need.
With Britecharts, you can also download individual bundles of the charts and helpers. To do this, you can [browse all CDN files][jsDelivrDist], browsing inside the `umd` folder to find the chart URL you need.
You can see the CDN links in action in:
* our [CDN demo page][cdnDemo]
* this [JSBin][jsbinSandbox] sandbox project
* this [CodePen][codepenSandbox] pen
## Building the source code
To build the soure code, you need first to get the code. You can do it by cloning or downloading it from Github.com. You can clone the git repository by running:
```
git clone https://github.com/britecharts/britecharts.git
```
Or download the source code by navigating to the [Release Page][githubReleases] and click in the latest's release `zip` or `tar.gz` links.
Then, you would need to install the dependencies and build the project. Check the [Contributing Guide][contributingGuide] to learn about this process.
## Summary
In this tutorial, you have seen three different ways of adding Britecharts to your site or web application.
To keep on learning more about Britecharts, you can follow our [Composing Your First Data Visualization][composingDataviz] or our [Styling Britecharts][stylingBritecharts] tutorials. You can also check out our [documentation Homepage][home] and our [kitchen sink][demos] to see all the available charts.
If you are excited about Britecharts, want to add more configurable properties or even create your own chart, please check our [Contributing Guide][contributingGuide]. In it, we walk you through the development environment setup, running our docs and demos and creating new Pull Requests.
[jsDelivrDist]: https://cdn.jsdelivr.net/npm/@britecharts/core/dist/
[cdnDemo]: https://github.com/britecharts/britecharts/blob/main/packages/integration/consumers/vanilla/cdn-jsdelivr.html
[jsbinSandbox]: https://jsbin.com/wativun/1/edit?html,js,output
[codepenSandbox]: https://codepen.io/Golodhros/pen/PprGeP?editors=1010
[contributingGuide]: https://github.com/britecharts/britecharts/blob/main/.github/CONTRIBUTING.md
[githubReleases]: https://github.com/britecharts/britecharts/releases
[home]: https://britecharts.github.io/britecharts/
[demos]: https://britecharts.github.io/britecharts/storybook/
[gettingStarted]: https://britecharts.github.io/britecharts/docs/tutorials/getting-started
[composingDataviz]: https://britecharts.github.io/britecharts/docs/tutorials/composing-dataviz
[stylingBritecharts]: https://britecharts.github.io/britecharts/docs/tutorials/styling-charts
---
# Composing Your First Data Visualization
Source: https://britecharts.github.io/britecharts/docs/tutorials/composing-dataviz
In the [Getting Started Guide][gettingStarted], we saw how to set up a responsive Bar chart using Britecharts. This tutorial was easy to follow; however, most of the times our real-world requirements include other components to help communicate our data.
In this tutorial, we will create a complex data visualization. You will learn how to draw a line chart with a tooltip, how to add a legend and a data filtering tool using a brush chart.
## Rendering a line chart
Let's build on top of the Bar Chart tutorial by using its code structure. We load the same bundle, which has every chart:
```html
```
Then, we will instantiate a line chart:
```js
const lineChart = core.line();
```
The shape of our data changed as well. We need to check the [line chart data schema][lineChartDataSchema] for this chart. In our case, it looks like this:
```js
const lineData = {
"data": [
{
"value": 0,
"name": -1,
"topicName": "Vivid",
"date": "2016-08-01T00:00:00-07:00"
},
{
"value": 3,
"name": 2,
"topicName": "Radiant",
"date": "2016-08-01T00:00:00-07:00"
},
...
]
};
```
Before configuring the chart, we figure out the container's size to apply it as the chart width:
```js
const container = document.querySelector('.line-container');
const containerWidth = container.getBoundingClientRect().width;
```
Configuring and rendering the line chart follows an identical approach as with the bar chart:
```js
lineChart
.margin({bottom: 50})
.height(400)
.width(containerWidth);
lineChart.render(container, lineData);
```
That renders the following chart:
![Simple Line Chart][lineChartImg]
## Adding a Tooltip
Now that we have a line chart working, we are going to add a tooltip to allow users to check the specific values on each date. We start by instantiating a new [Tooltip component][tooltipAPIReference]:
```js
const chartTooltip = core.tooltip();
```
Then we give it to the line chart:
```js
lineChart
.margin({bottom: 50})
.height(400)
.width(containerWidth)
.tooltip(chartTooltip);
lineChart.render(container, lineData);
```
The chart does the rest. It shows the tooltip when the pointer enters the chart, or when the keyboard moves to a date, updates it as they move, and hides it when they leave. It draws the tooltip in its hover marker, and tells the tooltip which fields of its data to read.
After the previous code, we will see a tooltip like the following:
![Line Chart with Tooltip][lineChartTooltipImg]
## Drawing a Legend
Up to now, we have been working with a dataset that contains only one topic. But what happens if we have two topics? In this section, we will update our data to contain another set of entries. We add a legend component to show our users which line corresponds to which topic.
First, we make a copy of the topic we already have and change some values. We named the new topic "Radiant," and due to our default color schema, it shows as a dark green line.
Now we instantiate our new [legend component][legendAPIReference]:
```js
const chartLegend = core.legend();
```
The same way as we needed a container for the chart, we require another for the legend:
```html
```
The legend is a component that depends on the data and in a specific data shape. We check the Legend data schema, and it needs to be:
```json
[
{
id: 1,
quantity: 2,
name: 'glittering'
},
{
id: 2,
quantity: 3,
name: 'luminous'
}
]
```
As we want to show an inline legend, which doesn't show the quantity, we only need one entry per line, with its name, an id and a quantity of zero. Here is how we create that data:
```js
// One entry per line: every point repeats its line's name and topicName
const legendData = Array.from(
new Map(
lineData.data.map(({ topicName, name }) => [
name,
{ id: name, name: topicName, quantity: 0 },
])
).values()
);
```
And we are ready to configure and draw the legend:
```js
chartLegend
.width(containerWidth)
.height(60)
.isHorizontal(true);
chartLegend.render('.legend-container', legendData);
```
Note how we have used the container width to position the legend in the center. You can see the rest of the options of the legend component in its [API reference page][legendAPIReference].
The resulting chart is:
![Line Chart with Legend][lineChartLegendImg]
## Filtering Data with a Brush
Our current data is not that extensive, but in theory, our line chart could render datasets of any size. This could be a problem as we could get into a position where the data points get too close, and our users can't see the details of the data. One way of fixing this is by allowing to filter data, and the way we do it visually is by using a brush chart.
In this section, we go over the process of adding a brush chart to our visualization, allowing to drag and drop a section of the data to zoom in that period.
### Creating the brush chart
Let's first instantiate the brush chart:
```js
const chartBrush = core.brush();
```
We would need to add its container to the DOM:
```html
```
Now, as we did before, we are going to check the [Brush Chart API][brushChartAPIReference] and its [data schema][brushChartDataSchema]. The data needs to look like this:
```json
[
{
value: 1,
date: "2011-01-06T00:00:00Z"
},
{
value: 2,
date: "2011-01-07T00:00:00Z"
}
]
```
So, in order to get this data shape, we will need to do some modifications to our line chart data:
```js
const brushData = lineData.data
.reduce(consolidateDatesReducer, []);
```
In the first reducer function, we obtain the entries by date, keeping only date and values. On the second one, we remove duplicated dates and sum up the values to have an aggregate of them. You can check the details of these functions in the [final code][composingDatavizTutorialHTML].
Now we are ready to configure and render our brush using the usual pattern:
```js
chartBrush
.width(containerWidth)
.height(100)
.xAxisFormat(chartBrush.axisTimeCombinations.DAY_MONTH)
.margin({top:0, bottom: 40, left: 50, right: 30});
chartBrush.render('.brush-container', brushData);
```
Notice that we are setting the x-axis format to a constant called `DAY_MONTH` within the axisTimeCombinations object. This `xAxisFormat` option is a way for us to select a date format that works for our data. In this case, it is the day of the month, as the default one (hours) was showing the same hour every day.
This code renders a simple Brush chart:
![Simple Brush Chart][brushChartImg]
This chart only serves as an overview of the sum of data in our dataset. What we want to do is, when we drag and drop a section of the brush, select that portion of our dataset and re-render the line chart with it.
For that, we listen to the `customBrushEnd` event on the brush, that returns the period of the brush selection. We take the beginning and end of that period and filter our original data with them. Finally, we apply it to the line chart and re-render. Here is the code for it:
```js
chartBrush
.width(containerWidth)
.height(100)
.xAxisFormat(chartBrush.axisTimeCombinations.DAY_MONTH)
.margin({ top: 0, bottom: 40, left: 50, right: 30 })
.on('customBrushEnd', ([brushStart, brushEnd]) => {
if (brushStart && brushEnd) {
let filteredLineData = filterData(brushStart, brushEnd);
lineChart.render(container, filteredLineData);
}
});
```
This results in a data visualization where we can focus on different sections of the data, and use our tooltip to see the values on those:
![Line with Brush, Tooltip and Legend][lineBrushTooltipLegendImg]
Here is the filtering logic for your reference:
```js
const isInRange = (startDate, endDate, {date}) => new Date(date) >= startDate && new Date(date) <= endDate;
const filterData = (brushStart, brushEnd) => {
// Copy the data
let data = JSON.parse(JSON.stringify(lineData));
data.data = data.data.filter(isInRange.bind(null, brushStart, brushEnd));
return data;
};
```
You can see the full code of this tutorial [in this file][composingDatavizTutorialHTML] and the [tutorial working here][composingDatavizTutorial].
## Summary
In this tutorial, we have seen how we can use different support components like the legend and tooltip to provide information about our charts. We also saw how we could use the brush chart to provide a high-level view of our dataset. We saw how to configure the brush to filter the data and how to reload our main chart with this new data.
To learn more, you can read our [Styling Britecharts tutorial][stylingBritecharts] or check our demos and documentation. If you decided to use Britecharts in your project, you could follow the [Installing Britecharts tutorial][installingBritecharts] to learn what's the better way to use Britecharts. Check also the [Topics page][topicsIndex] to learn more about our approach.
If you are excited about Britecharts, want to add more configurable properties or even create your own chart, please check our [Contributing Guide][contribute]. In it, we walk you through the development environment setup, running our docs and demos and creating new Pull Requests.
[gettingStarted]: https://britecharts.github.io/britecharts/docs/tutorials/getting-started
[stylingBritecharts]: https://britecharts.github.io/britecharts/docs/tutorials/styling-charts
[installingBritecharts]: https://britecharts.github.io/britecharts/docs/tutorials/installing-britecharts
[lineChartImg]: https://raw.githubusercontent.com/britecharts/britecharts/main/packages/docs/static/img/tutorial/simple-line-chart.png
[composingDatavizTutorialHTML]: https://github.com/britecharts/britecharts/blob/main/packages/docs/docs/tutorials/html/tutorial-composing-dataviz.html
[composingDatavizTutorial]: https://britecharts.github.io/britecharts/docs/tutorials/composing-dataviz
[lineChartAPIReference]: https://britecharts.github.io/britecharts/docs/API/line
[lineChartDataSchema]: https://britecharts.github.io/britecharts/docs/API/line#module_Line--exports..LineChartData
[tooltipAPIReference]: https://britecharts.github.io/britecharts/docs/API/tooltip
[lineChartTooltipImg]: https://raw.githubusercontent.com/britecharts/britecharts/main/packages/docs/static/img/tutorial/line-chart-tooltip.png
[legendAPIReference]: https://britecharts.github.io/britecharts/docs/API/legend
[lineChartLegendImg]: https://raw.githubusercontent.com/britecharts/britecharts/main/packages/docs/static/img/tutorial/line-chart-legend.png
[brushChartAPIReference]: https://britecharts.github.io/britecharts/docs/API/brush
[brushChartDataSchema]: https://britecharts.github.io/britecharts/docs/API/brush#module_Brush--exports..BrushChartData
[brushAxisCombinations]: https://britecharts.github.io/britecharts/docs/API/brush#module_Brush--exports.axisTimeCombinations
[brushChartImg]: https://raw.githubusercontent.com/britecharts/britecharts/main/packages/docs/static/img/tutorial/simple-brush-chart.png
[lineBrushTooltipLegendImg]: https://raw.githubusercontent.com/britecharts/britecharts/main/packages/docs/static/img/tutorial/line-chart-with-brush-tooltip-legend.png
[topicsIndex]: https://britecharts.github.io/britecharts/docs/topics/topics-index
[contribute]: https://github.com/britecharts/britecharts/blob/main/.github/CONTRIBUTING.md
---
# Styling Britecharts
Source: https://britecharts.github.io/britecharts/docs/tutorials/styling-charts
In the [Getting Started Guide][gettingStarted] and the [Composing Your First Data Visualization tutorial][composingDataviz] we saw how to create and configure Britecharts. We have created beatiful charts, however, users have specific branding and styling needs that want to get in their charts to adapt to their user interfaces.
In this tutorial, we will go over the **different options we have to customize Britechart**s. You will learn how you can use Britechart's color schemas to change the charts colors or customize your own. We will also see how to override the CSS styles that come with Britecharts and how to update the fonts.
## Applying a color palette
Let's look at some customization options we have available for Britecharts. The first one is the color schemas and gradients. You can find some of them in our [Color Palettes demo page][colorPalettesDemo].
To get us started with a tutorial, we are going to take our [Getting Started tutorial][gettingStarted] code and create [a new HTML file][stylingBritechartsHTML] based on it.
We will start from the code we got at the end of that tutorial, removing the responsive part:
```js
// Instantiate Bar Chart
const barChart = core.bar();
// Create Dataset with proper shape
const barData = [
{ name: 'Luminous', value: 2 },
{ name: 'Glittering', value: 5 },
{ name: 'Intense', value: 4 },
{ name: 'Radiant', value: 3 }
];
// Configure chart
barChart
.margin({ left: 100 })
.isHorizontal(true)
.height(400)
.width(600);
barChart.render('.bar-container', barData);
```
Starting with this bar chart, we want to customize the color palette. The color schemas come with the bundle, as `core.colors`, so we can set the color schema of the bar chart by doing:
```js
// Configure chart
barChart
.colorSchema(core.colors.colorSchemas.orange)
.margin({ left: 100 })
.isHorizontal(true)
.height(400)
.width(600);
```
That renders an orange bar chart:
![Orange Bar Chart][orangeBarChartImg]
The different color palettes we provide in Britecharts are ubicated within the `colorSchemas` object. You can see their colors them in the [demo page][colorPalettesDemo].
When we look at the palettes code, they are just an array of nine hexadecimal values. For example:
```js
// Britecharts palette
["#6aedc7", "#39c2c9", "#ffce00", "#ffa71a", "#f866b9", "#998ce3"]
```
Which means that if you want to customize your charts color palette, you only need to pass an array of hexadecimal colors into the `.colorSchema` accessors.
## Using a color gradient
Some Britecharts use a color gradient for their lines (line, sparkline and stacked area charts) or for the body of the chart (brush).
You can find these color gradients in `core.colors.colorGradients` and similarly, they are an array of colors. However, in this case they are only two colors, one for the beginning and another for the end of the gradient.
## Overriding default styles
Whenever we want to change the font family, font sizes or any other styling detail of our charts, we can do so by creating CSS overrides. As an example, let's change the font of our bar chart.
We'll begin by looking for a new font in [Google Fonts][gFonts]. I am a fan of the font `Oswald`, so let's add it to our tutorial by including this link tag in the header:
```html
```
Now, we need to set up a style override. For that, we can inspect our SVG elements with the dev tools of our browser. In this case, we see that the `font-family` attribute is set by the `.britechart` class. To override it, we need to add a `style` tag after the link that loads the default britecharts styling and inside the tag, include following code:
```html
```
This CSS code will override the `font-family` definition for both the whole chart and the specific tick text of our axes. If we also change the color schema to the red palette, we get this chart:
![Red Bar Chart][redBarChartImg]
We could follow the same steps to style most of Britechart's styling. One caveat is that, given that Britecharts is an SVG based library, the styling of SVG elements is sometimes different. In those cases, check out this [SVG styling guide][svgReference] to make sure you are updating the right properties.
## Summary
In this tutorial, you saw how you can use Britecharts' color helper to apply color palettes and color gradients to your charts. You also saw you can customize all the elments by using CSS style overrides. You can see the [tutorial code working here][stylingBritechartsTutorial].
To learn more, you can follow our [Composing Your First Data Visualization tutorial][composingDataviz]. You can also check out our [Documentation Homepage][home] and our [kitchen sink][demos] to see all the available charts.
[home]: https://britecharts.github.io/britecharts/
[demos]: https://britecharts.github.io/britecharts/storybook/
[gettingStarted]: https://britecharts.github.io/britecharts/docs/tutorials/getting-started
[composingDataviz]: https://britecharts.github.io/britecharts/docs/tutorials/composing-dataviz
[colorPalettesDemo]: https://britecharts.github.io/britecharts/storybook/core/?path=/story/attributes-colors--color-schemas
[stylingBritechartsHTML]: https://github.com/britecharts/britecharts/blob/main/packages/docs/docs/tutorials/html/tutorial-styling-britecharts.html
[stylingBritechartsTutorial]: https://britecharts.github.io/britecharts/docs/tutorials/styling-charts
[orangeBarChartImg]: https://raw.githubusercontent.com/britecharts/britecharts/main/packages/docs/static/img/tutorial/orange-bar-chart.png
[redBarChartImg]: https://raw.githubusercontent.com/britecharts/britecharts/main/packages/docs/static/img/tutorial/red-bar-chart.png
[gFonts]: https://fonts.google.com/
[svgReference]: https://www.smashingmagazine.com/2014/11/styling-and-animating-svgs-with-css/
---
# User How-To Guides
Source: https://britecharts.github.io/britecharts/docs/how-tos/user-how-to-guides
Our how-to guides are recipes to address specific and critical use cases when working with Britecharts. They assume some knowledge about Britecharts and the library structure. If this is the first time you work with Britecharts, we recommend you to read the [Getting Started Tutorial][gettingStarted] first.
## How to Customize the Chart's Colors
Follow these steps to customize Britecharts' charts to use different color schemas:
1. Find out if your chart supports the `.colorSchema()` configuration, if so, keep on reading
1. Check the [Color Palettes demo page][colorPalettesDemo] and find a palette you like
1. Import the `colors` helper at the top of your file
1. Set the color palette with `.colorSchema(colors.colorSchemas.orange)` or with any other color schema
1. Draw the chart
For readers with colour blindness, use `colors.colorSchemas.okabeIto`. Its eight colours, from Okabe and Ito's palette, stay distinct with the common kinds of colour blindness. Black comes last, so charts with up to seven categories never draw a series in black. Its yellow, orange and sky blue are light on a white background, so the palette suits filled marks such as bars and donut slices better than thin lines. Colour shouldn't be the only thing that tells series apart: a legend or labels help every reader.
Note that in some charts we can only configure a gradient. Use the `colorGradients` object instead of `colorSchemas` within the colors helper. You can explore other options in the source code of the [colors file][colorsHelper].
### Give each category its own colour
A palette assigns colours in order, so a category's colour changes when the data does. To pin one colour to each category, pass `colorMap` an object from category to colour:
```js
barChart.colorMap({
Shiny: '#39c2c9',
Blazing: '#fcc870',
});
```
A category the map leaves out keeps its palette colour. Each chart matches the keys against one field of its data:
| Chart | `colorMap` keys match |
| --- | --- |
| Bar, donut, scatter plot, stacked area | `name` |
| Line | `name`, the topic's identifier (not `topicName`) |
| Stacked bar | `stack` |
| Grouped bar | `group` |
The legend takes `colorMap` too: pass it the same object so its entries match the chart. In React, `colorMap` is a prop with the same shape.
## How to Theme a Chart and Support Dark Mode
Everything around the data (text, axes, grid lines, tooltips, the legend, loading skeletons) takes its colour from a CSS custom property. Each defaults to a light and a dark value, picked by the [`color-scheme`](https://developer.mozilla.org/en-US/docs/Web/CSS/color-scheme) the chart inherits from your page.
To follow the system's light or dark setting, declare both schemes on your page:
```css
:root {
color-scheme: light dark;
}
```
To force one, set `color-scheme: light` or `color-scheme: dark` on the page, or on any element around the chart. An app with its own light/dark switch sets it there. A page that declares no colour scheme keeps the charts light, as before.
To change a colour, set its token on the charts:
```css
.britechart {
--bc-text-muted: #555;
--bc-background: #10141a; /* the colour behind your charts */
}
```
| Token | Colours |
| --- | --- |
| `--bc-text` | tooltip values and other primary text |
| `--bc-text-muted` | tick labels, data labels, tooltip titles |
| `--bc-text-subtle` | axis titles |
| `--bc-axis` | tick marks, the lines that extend the axes, custom line annotations |
| `--bc-grid`, `--bc-grid-highlight` | grid lines, and a highlighted one |
| `--bc-background` | what is behind the chart: the line chart's drawing mask and an export's background. It defaults to `Canvas`, the page's background in the current scheme; set it if your page uses another. |
| `--bc-surface` | the tooltip box, data point markers, hollow circles, heatmap borders |
| `--bc-border` | the tooltip's border and the hover marker |
| `--bc-skeleton`, `--bc-skeleton-strong` | loading states |
| `--bc-brush-area`, `--bc-brush-area-missing` | the brush's area, and its gaps |
| `--bc-sparkline-area-start`, `--bc-sparkline-area-end` | the sparkline's default area gradient |
The data colours come from `colorSchema` and `colorMap`, not from these tokens. Exports carry the resolved colours, so an image exported in dark mode keeps its dark background. Browsers without `light-dark()` (before 2024) show the light values.
## How to Add a Tooltip to a Chart
Give the chart a tooltip with its `tooltip` setting. The same `tooltip()` works on every chart that takes one: the line, stacked area, stacked bar and grouped bar charts list one row per topic, and the bar, heatmap and scatter plot show one value. It has no title until you set one, and it shows a single value with two decimals unless you set a `numberFormat`. The donut has no tooltip: it shows the hovered slice in its centre instead.
```js
stackedBar()
.tooltip(tooltip().title('Visits'))
.render('.js-chart', data);
```
The chart does the rest, on every draw. It shows the tooltip when the pointer or the keyboard reaches a data point, moves it as they move and hides it when they leave. It draws the tooltip in place, and sets the labels that tell the tooltip which fields of its data points to read, unless you set them on the tooltip yourself. Set `tooltip(null)` to remove it. A tooltip belongs to one chart, so give each chart its own.
### Connect a tooltip by hand
To change the data point before the tooltip shows it, connect the tooltip yourself.
Drawing the tooltip by hand takes d3's `select`, which the `tooltip` setting does not need. With npm, run `npm install d3-selection` and import `select` from it. On a CDN page, add `` and call `d3.select`.
1. Connect the chart's `customMouseOver`, `customMouseMove` and `customMouseOut` events to the tooltip's `show`, `update` and `hide`
1. Tell the tooltip where the chart keeps its data, if the table below lists a setting for it
1. Draw the chart, then call the tooltip on the chart's `.metadata-group` (for the line and stacked area, on `.metadata-group .vertical-marker-container`)
```js
import { stackedBar, tooltip } from '@britecharts/core';
import { select } from 'd3-selection';
const stackedBarChart = stackedBar();
const chartTooltip = tooltip()
.topicLabel('values')
.nameLabel('stack');
stackedBarChart
.on('customMouseOver', chartTooltip.show)
.on('customMouseMove', chartTooltip.update)
.on('customMouseOut', chartTooltip.hide)
.render('.js-chart', data);
select('.js-chart .metadata-group').datum([]).call(chartTooltip);
```
The charts do not all name the fields of the data point they send the tooltip the same way, so some need a setting. The `tooltip` setting sets these for you. By hand, or with React's `Tooltip`, set them yourself; without them, the tooltip shows no rows, rows without their colours, or no value:
| Chart | Tooltip settings | React `Tooltip` props |
| --- | --- | --- |
| Line | none | `topicLabel="topics"` |
| Stacked area | `topicLabel('values')` | none |
| Stacked bar | `topicLabel('values')`, `nameLabel('stack')` | `nameLabel="stack"` |
| Grouped bar | `topicLabel('values')`, `nameLabel('group')` | `nameLabel="group"` |
| Scatter plot | `valueLabel('y')` | `valueLabel="y"` |
| Bar, heatmap | none | none |
React's `Tooltip` starts from `topicLabel('values')`, which is why the line chart is the one that needs a prop there. The [tooltip reference][tooltipAPI] describes each setting, and the [Storybook][storybook] shows each chart with its tooltip configured.
## How to Format Numbers and Dates for Your Language
Three settings control how values read. They do different things, so check which one a chart has in its [API reference][apiReference]:
* `numberFormat` takes a [d3-format specifier][formatSpecifiers], such as `',.2f'` for two decimals with a thousands separator, or `'.0%'` for a percentage. It formats the values on the chart's axes and labels; the tooltip has a `numberFormat` of its own.
* `valueLocale` takes a [d3-format locale definition][formatLocale] and sets the separators and currency those values use. The bar, grouped bar, stacked bar and scatter plot charts have it. The definition needs at least `decimal`, `thousands`, `grouping` and `currency`, or the chart throws.
* `locale` takes a language tag such as `'fr-FR'`, and localizes the dates in the tooltip and the brush with `Intl.DateTimeFormat`.
```js
barChart
.numberFormat(',.2f')
.valueLocale({
decimal: ',',
thousands: '.',
grouping: [3],
currency: ['', ' €'],
});
// The axis reads 1.000,00 instead of 1,000.00
```
Negative numbers use the typographic minus sign (`−`), as d3-format does. To get the ASCII hyphen back, add `minus: '-'` to the locale definition.
Each chart keeps its `valueLocale` to itself, so two charts on a page can use different ones.
## How to Show a Loading State
Every data chart can draw a skeleton in its own shape while the data loads:
1. Set `isLoading(true)` and draw the chart with whatever data you have, even an empty array
1. When the data arrives, set `isLoading(false)` and draw the chart again with it
```js
barChart.isLoading(true).render('.js-chart', []);
fetchData().then((data) => {
barChart.isLoading(false).render('.js-chart', data);
});
```
In React, pass `isLoading` together with the data you have, an empty array included, and set it to `false` when the data arrives. With `data={null}`, the component draws nothing at all, skeleton included.
## How to Animate a Chart
Charts draw without animation by default. Set `isAnimated(true)` to animate them as they draw, and `animationDuration` to set how long that takes, in milliseconds (1200 by default):
```js
lineChart.isAnimated(true).animationDuration(600);
```
`animationDuration` does nothing while `isAnimated` is `false`. The bar, grouped bar, stacked bar, line, stacked area, donut, heatmap, treemap, scatter plot, sparkline and brush charts animate. React components take both as props.
A reader whose system asks for reduced motion (the `prefers-reduced-motion` setting) sees every chart drawn without animation, whatever `isAnimated` is set to. Charts check it each time they draw, so changing the setting applies from the next render. `isAnimated()` still reads back the value you set. The rest of the motion stops too: tooltips appear and move without fading or easing, the legend drops entries without a fade, and a hovered point is highlighted without its bounce.
## How to Export a Chart
Call `exportChart` with a filename to download the chart as it is drawn. The filename picks the format: one ending in `.svg` downloads an svg file, and any other a png. An optional second argument adds a title at the top:
```js
barChart.exportChart('visits.svg', 'Visits by month');
barChart.exportChart('visits.png');
```
The svg keeps the chart's styles inlined, so it looks the same in a design tool or a document, and it stays sharp at any size. `exportChart` returns a promise that resolves once the download starts. In React, every chart component except `Brush` and `Legend` takes the filename as its `exportChart` prop. Setting it downloads the chart once, so set a new filename to download again.
## How to Chart Negative Values
The bar, grouped bar, stacked bar, brush and scatter plot charts draw negative values with no setting to turn on:
* The bar charts draw bars below, or to the left of, a zero baseline, and a stacked bar stacks its negative parts down from zero.
* The scatter plot's value axis runs below zero when the data does, and a circle's size shows the size of its value, so -50 draws as large as 50.
The line and stacked area charts plot negative values as they are. Axis labels for negative numbers use the typographic minus sign: see [how to format numbers](https://britecharts.github.io/britecharts/docs/how-tos/user-how-to-guides#how-to-format-numbers-and-dates-for-your-language) to change it.
## How to Make a Chart Accessible
For an overview with live charts to try, and how other libraries compare, see [Accessible JavaScript Charts](https://britecharts.github.io/britecharts/docs/accessibility).
Every chart gives its svg a role and a name that screen readers announce: "Bar chart" by default. Name it after what it shows, and add a sentence about what it means:
```js
barChart
.a11yTitle('Monthly visits')
.a11yDescription('Visits doubled in May');
```
The name goes in an `aria-label`, so browsers do not show it as a tooltip on hover. React components take `a11yTitle` and `a11yDescription` as props.
### Read the data as a table
Every chart but the legend also renders its data as a table, right after its svg, which screen readers reach as a table: they can read it row by row, move along a row or down a column, and hear each cell's headings. It is hidden from sight, takes no room on the page, and is linked from the chart with `aria-details`. Its caption is the chart's name, so set `a11yTitle` and the table is named after it too.
Charts with several series lay it out wide, as a reader would expect: a line chart has a row per date and a column per topic, and a heatmap a row per day and a column per hour.
The table is on by default. If your page already shows the data in an accessible form, turn it off:
```js
barChart.a11yDataTable(false);
```
In React, pass `a11yDataTable={false}`; in the wrappers, `a11yDataTable: false` in the configuration.
### Move through the data with a keyboard
The bar, donut, grouped bar, heatmap, line, scatter plot, stacked area and stacked bar charts can be explored without a pointer. Each chart is one stop in the page's tab order; once it has focus:
| Key | Does |
| --- | --- |
| Right or Left arrow | moves to the next or previous data point: a bar, a slice, a date, a point |
| Down or Up arrow | the same, except on the heatmap, where they move a day |
| Home, End | moves to the first or last point |
| Escape | lets go of the point; leaving the chart does too |
The chart responds as it does to a pointer: the point is highlighted, the tooltip follows focus, and the `customMouseOver`, `customMouseMove` and `customMouseOut` events fire, so your own hover code works from the keyboard too. The browser's focus ring shows which chart has focus.
It is on by default. To take the charts out of the tab order, for example in a list of thumbnails, turn it off:
```js
barChart.a11yKeyboardNavigation(false);
```
In React, pass `a11yKeyboardNavigation={false}`; in the wrappers, `a11yKeyboardNavigation: false` in the configuration.
### Label a bullet chart or a sparkline
The bullet chart and the sparkline draw only their data, with no title: text inside an svg cannot wrap and ignores the page's typography. Put the label in your own markup, next to the chart, and give screen readers the same words:
```html
CPU load GHz
```
```js
bulletChart.a11yTitle('CPU load, GHz').render('.js-bullet-chart', data);
```
## How to Describe a Chart as a Spec and Check It
A chart can be written down as a spec, a plain object with its name, its configuration and its data, which you can store, send from a server, or have a coding agent write:
```json
{
"$schema": "https://britecharts.github.io/britecharts/schema/v3/bar.json",
"chart": "bar",
"config": { "isHorizontal": true, "a11yTitle": "Signups by plan" },
"data": [{ "name": "Pro", "value": 412 }]
}
```
Each chart has a JSON Schema for its spec at `https://britecharts.github.io/britecharts/schema/v3/.json`: `bar`, `brush`, `bullet`, `donut`, `groupedBar`, `heatmap`, `legend`, `line`, `scatterPlot`, `sparkline`, `stackedArea`, `stackedBar`, `tooltip` and `treemap`. They are generated from the charts' TypeScript types, so they list every accessor with its type and description. With the `$schema` line, editors such as VS Code check and complete the spec as you type, and any JSON Schema validator (Ajv, for example) can check one before you draw it.
Draw a spec with the chart's wrapper, which checks it too:
```js
import { BarWrapper } from '@britecharts/wrappers';
BarWrapper.create(element, spec.data, spec.config);
```
A key the chart doesn't have, or a value of the wrong type, throws an error that names each one and says what it should be. Options that take a function, such as the events and the formatting functions, can't be written in JSON: set them from JavaScript.
## How to Add a Chart to a shadcn App
Britecharts has a [shadcn registry](https://ui.shadcn.com/docs/registry), so in an app set up with shadcn/ui one command adds a chart:
```bash
npx shadcn@latest add https://britecharts.github.io/britecharts/r/bar-chart.json
```
It copies a component into `components/charts/bar-chart.tsx`, installs `@britecharts/react` and `@britecharts/core`, and adds a rule to your CSS that colours the charts with your shadcn theme: text with `--foreground` and `--muted-foreground`, axes and grid with `--border`, tooltips with `--popover`. The charts follow your app's light and dark modes, and the data keeps Britecharts' palettes. The component is yours to edit.
```tsx
import { BarChart } from '@/components/charts/bar-chart';
;
```
Each chart fills the width of its container, so put it in an element that has a width, and comes with its tooltip set up. Every other prop is the chart's own, as on its API page.
| Chart | Add it with |
| --- | --- |
| Bar | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/bar-chart.json` |
| Grouped bar | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/grouped-bar-chart.json` |
| Line | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/line-chart.json` |
| Scatter plot | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/scatter-plot.json` |
| Stacked area | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/stacked-area-chart.json` |
| Stacked bar | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/stacked-bar-chart.json` |
| Heatmap | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/heatmap.json` |
| Treemap | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/treemap.json` |
| Donut | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/donut-chart.json` |
| Sparkline | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/sparkline.json` |
| Brush | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/brush.json` |
| Bullet | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/bullet-chart.json` |
| Legend | `npx shadcn@latest add https://britecharts.github.io/britecharts/r/legend.json` |
The registry's index, for `shadcn list` and shadcn's MCP server, is at `https://britecharts.github.io/britecharts/r/registry.json`.
## How to Configure Time Scales
Britecharts has some logic to try guessing the best date format on time series charts from the time period of the dataset. As we haven't bulletproofed this algorithm, and sometimes users want specific formats, we also expose configuration options to set custom formats.
The next steps apply to time series charts like the line chart, stacked area chart and brush chart:
1. Render the chart using the default settings, see if the x-axis format is satisfactory. If not, keep on reading.
1. Check the chart's reference to find out the configuration options, for example, the [line chart reference][lineChartAPI]
1. Check the options within the `axisTimeCombinations` object of the chart instance:
```
console.log('combinations', line.axisTimeCombinations);
// Returns
{
MINUTE_HOUR: 'minute-hour',
HOUR_DAY: 'hour-daymonth',
DAY_MONTH: 'day-month',
MONTH_YEAR: 'month-year',
CUSTOM: 'custom'
}
```
1. Set the `xAxisFormat` parameter to a value from the ones below (except 'custom')
1. Draw the chart and see if it meets your criteria. If not, try with other time combination. If still doesn't feel right, see next step.
1. Set the `xAxisFormat` parameter to the value `'custom'`
1. Set the `xAxisCustomFormat` parameter to a valid [D3.js time format specifier string][timeFormatSpecifiers]. For example: `line.xAxisCustomFormat('%H')`
1. Play around with different specifiers until finding something that works. You can experiment in [this block example][timeFormatsBlock].
Remember that for increased accuracy, all date formats in Britecharts should be provided in [ISO 8601 Extended Format][ISOFormat].
[gettingStarted]: https://britecharts.github.io/britecharts/docs/tutorials/getting-started
[colorPalettesDemo]: https://britecharts.github.io/britecharts/storybook/core/?path=/story/attributes-colors--color-schemas
[colorsHelper]: https://github.com/britecharts/britecharts/blob/main/packages/core/src/charts/helpers/color.ts
[ISOFormat]: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
[lineChartAPI]: https://britecharts.github.io/britecharts/docs/API/line
[tooltipAPI]: https://britecharts.github.io/britecharts/docs/API/tooltip
[apiReference]: https://britecharts.github.io/britecharts/docs/API/bar
[formatSpecifiers]: https://github.com/d3/d3-format#locale_format
[formatLocale]: https://github.com/d3/d3-format#formatLocale
[storybook]: https://britecharts.github.io/britecharts/storybook/
[timeFormatSpecifiers]: https://github.com/d3/d3-time-format#locale_format
[timeFormatsBlock]: https://bl.ocks.org/zanarmstrong/ca0adb7e426c12c06a95
---
# Migration Guide from version 2 to version 3
Source: https://britecharts.github.io/britecharts/docs/how-tos/migration-guide-2-to-3
:::note
Version 3.0 is in beta: `@britecharts/core`, `@britecharts/wrappers` and `@britecharts/react` publish `3.0.0-beta` releases under the `beta` tag (`npm install @britecharts/core@beta`). `3.0.0-beta.6` is the last beta before 3.0.0. The last stable release is still `britecharts@2.18.2`. This guide describes the migration to 3.0 and is kept up to date until the release.
:::
Version 3.0 of Britecharts fixes many bugs, improves loading and animation performance, and adds minor features. It also introduces breaking changes that make the components' APIs and data shapes more consistent, and moves the library to the `@britecharts` scope on npm: `britecharts` becomes `@britecharts/core`, and `britecharts-react` becomes `@britecharts/react`. Both are now written in TypeScript.
When it lands, we recommend migrating as soon as possible to get all these benefits. For that, we have prepared the following migration guide.
## Migration Steps
Most of the migration tasks involve changing accessor names, but there are also changes in how we load the modules. Follow these steps to get your application updated in no time:
### Breaking changes
1. Update the way you load the charts
We moved Britecharts internally from the outdated AMD modules into ES Modules, which changed how you will import the components. See below some examples:
```js
// Version 2
// For ES modules
import bar from 'britecharts/dist/umd/bar.min';
// For AMD and CommonJS modules
const LineChart = require('britecharts/umd/line.min');
// Version 3
// As ES modules
import { bar } from '@britecharts/core';
// As CommonJS modules
const { bar } = require('@britecharts/core');
```
The stylesheets move too. `britecharts/dist/css/britecharts.min.css` is now `@britecharts/core/dist/styles/bundle/britecharts.min.css`, and each chart's own stylesheet is under `@britecharts/core/dist/styles/charts/`.
You can also check more ways of loading (CommonJS, UMD and CDN) in the [vanilla consumer](https://github.com/britecharts/britecharts/tree/main/packages/integration/consumers/vanilla) of our integration tests, which CI runs against every change
2. Change how you show loading states
Search for any use of the 'loadingState' accessor for getting the loading state, and render the chart with 'isLoading' as true and a valid dataset (it can be empty).
```js
// Version 2
barContainer.html(barChart.loadingState())
// Version 3
barChart
.width(containerWidth)
.height(300)
.isAnimated(true)
.isLoading(true)
.render(barContainer, dataset);
```
3. Use 'valueLocale' to format values
You must use the 'valueLocale' accessor to set the locale object (see [the d3-format docs](https://github.com/d3/d3-format#formatLocale)) of the component´s rendered values (axes ticks, numerical values, etc.).
Before, this used to be ´locale´ in the bar, grouped bar, scatted bar, and scatter plot.
```js
// Version 2
barChart
.locale({
thousands: '.',
grouping: [3],
currency: ["$", ""],
decimal: "."
})
//...other configurations
// Version 3
barChart
.valueLocale({
thousands: '.',
grouping: [3],
currency: ["$", ""],
decimal: "."
})
//...other configurations
```
In contrast, for time series charts (lineChart, stackedAreaChart), we use 'locale' to pass the language tag for the tooltip to localize the *date*. It uses Intl.DateTimeFormat, for compatibility and support.
4. Swap the use 'xAxisCustomFormat' and 'xAxisFormat' on brush charts
Whenever you were using 'xAxisCustomFormat' in a brush chart, now you should use 'xAxisFormat', and viceversa.
```js
// Version 2
brush
.xAxisCustomFormat('custom')
.xAxisFormat('%A');
// Version 3
brush
.xAxisCustomFormat('%A')
.xAxisFormat('custom');
```
This made this configuration consistent with the line and stacked area charts.
5. Use 'numberFormat' in bar charts
Search for uses of 'valueLabelFormat' and change them to 'numberFormat':
```js
// Version 2
groupedBarChart
.valueLabelFormat(',s')
// other configurations
// Version 3
groupedBarChart
.numberFormat(',s')
// other configurations
```
The 'numberFormat' configuration is available for the bar, bullet, donut, grouped bar, stacked-bar, legend, line, mini-tooltip, and tooltip components.
6. Stop using 'aspectRatio' to set charts' dimensions
We eliminated the 'aspectRatio' accessor from our charts. Instead, use the 'width' and 'height' attributes to set a explicit size and leave the chart to respond to container width changes.
```js
// Version 2
lineChart
.width(100)
.aspectRatio('0.5');
// Version 3
lineChart
.width(100)
.height(50)
```
7. Expect the typographic minus sign in negative axis labels
Britecharts v3 runs on the current d3 modules, and d3-format changed its default minus sign from the ASCII hyphen (`-`, U+002D) to the typographic minus (`−`, U+2212). Negative values on axes and in tooltips now render with the latter.
Nothing to change unless you assert on that text — snapshot tests and string comparisons against axis labels will need updating. If you would rather keep the ASCII hyphen, set it through a value locale on the charts that have one (the bar, grouped bar, stacked bar and scatter plot). The definition needs `decimal`, `thousands`, `grouping` and `currency` as well:
```js
barChart.valueLocale({
decimal: '.',
thousands: ',',
grouping: [3],
currency: ['$', ''],
minus: '-',
});
```
8. Use the d3 v7 modules alongside Britecharts
Britecharts v3 runs on the d3 v7 generation of the `d3-*` modules. They are dependencies of `@britecharts/core`, so installing it from npm installs them, and the ES module and `dist/umd` builds load them from there rather than bundling them. If your own code uses d3 together with Britecharts, upgrade it to v7 at the same time. The CDN builds under `dist/cdn` bundle their own copy of d3 and need nothing else on the page.
The two d3 modules Britecharts used that are now deprecated upstream, `d3-collection` and `d3-voronoi`, have been replaced internally by `d3-array` and `d3-delaunay`. They are no longer dependencies.
9. Replace the 'dataByTopic' line chart data shape
The line chart no longer accepts the `dataByTopic` array it required up to 2.10.1. It has taken a flat `data` array since then, and that is now the only shape it accepts. Passing `dataByTopic` throws.
```js
// Version 2
lineChart.datum({
dataByTopic: [
{
topicName: 'San Francisco',
topic: 123,
dates: [
{ date: '2017-01-16T16:00:00-08:00', value: 1 },
{ date: '2017-01-17T16:00:00-08:00', value: 2 }
]
}
]
});
// Version 3
lineChart.datum({
data: [
{ topicName: 'San Francisco', name: 123, date: '2017-01-16T16:00:00-08:00', value: 1 },
{ topicName: 'San Francisco', name: 123, date: '2017-01-17T16:00:00-08:00', value: 2 }
]
});
```
One entry per point instead of points nested under each topic, and the topic identifier moves from `topic` to `name`. Britecharts groups the data internally, so nothing else about how you configure the chart changes.
If you have data in the old shape, this converts it:
```js
const toFlatData = ({ dataByTopic }) =>
dataByTopic.flatMap((topic) =>
topic.dates.map(({ date, value }) => ({
topicName: topic.topicName,
name: topic.topic,
date,
value,
}))
);
```
10. Update custom tooltip handlers on the line, stacked area, stacked bar and grouped bar charts
Every chart now dispatches `customMouseMove` with the same payload: the hovered data point, its anchor `[x, y]` in pixels relative to the chart's drawing area, the chart's `[width, height]`, and, from these four charts, the map of topic names to colours. Before, they dispatched `(dataPoint, colorMap, x, y)`. If you wire the tooltip directly, nothing changes; a handler of your own that reads the arguments by position has to take the new order. `tooltip.update` still accepts the old order in 3.x and warns once.
```js
// Version 2
lineChart.on('customMouseMove', function (dataPoint, colorMap, x, y) {
chartTooltip.update(dataPoint, colorMap, x, y);
trackHover(dataPoint, x);
});
// Version 3
lineChart.on('customMouseMove', function (dataPoint, [x, y], size, colorMap) {
chartTooltip.update(dataPoint, [x, y], size, colorMap);
trackHover(dataPoint, x);
});
// Either version
lineChart.on('customMouseMove', chartTooltip.update);
```
With that, `tooltip` and `miniTooltip` are one component: `tooltip` shows a list or a single value by the shape of the data point (or as told by `layout`), so use `tooltip()` everywhere. `miniTooltip()` still works but is deprecated, logs a warning and goes in version 4. `tooltip()` also no longer shows the placeholder "Tooltip title": if your tooltips relied on it, set `title`. The tooltip now keeps itself inside the chart, follows the pointer (the stacked and grouped bar charts show it over a bar only), and its `tooltipOffset` default is `{ x: 0, y: 0 }` (it was `{ x: 0, y: -55 }`, for a placement that no longer exists). `xAxisValueType` defaults to `'auto'`, which shows dates as dates, numbers as numbers and category names as they are; set `'date'` or `'number'` to force one, as before. In React, `Tooltip`'s `customMouseMove` callback receives the new order, and `Tooltip` now wraps the bar, scatter plot and heatmap charts too.
11. Replace the Step chart
The Step chart is removed from every package: the `step` export of `@britecharts/core`, its `StepWrapper` and the React `Step` component, with their stylesheets and builds. A bar chart draws the same data.
12. Transpile for older browsers yourself
The builds now target ES2020 instead of ES5. Every current browser runs them as they are. If you support a browser older than that, transpile Britecharts in your own build, as you would any package that ships modern syntax.
13. Move from `britecharts-react` to `@britecharts/react`
The React components are published as `@britecharts/react`, and they work differently in a few ways you may rely on:
```js
// Version 2
import { Bar } from 'britecharts-react';
// Version 3
import { Bar } from '@britecharts/react';
```
* React 16.8 or later is required, since the components are now function components built on hooks. They have no instances any more, so a `ref` on a chart component is not accepted.
* A chart redraws only when its props change. If you update your data by mutating it in place, pass a new array or object instead.
* `data` is required. Pass `null` while it loads: the chart draws nothing until the data arrives.
* `false`, `0` and `''` now reach the chart, so `isLoading={false}` ends a loading state. Leave a prop out, or pass `undefined`, to keep the chart's default.
* PropTypes are gone. Each component's props type is exported from the package root (`BarChartProps`, `LineProps` and so on) for TypeScript projects.
* `StackedBar`'s `nameLabelFormat` prop is removed. No chart had that setting, so passing it threw.
* `axisTimeCombinations` is no longer a prop of `Line`, `StackedArea` or `Tooltip`. Import the `axisTimeCombinations` constant from the package and pass one of its values to `xAxisFormat`.
14. Label bullet charts and sparklines outside the chart
The bullet chart no longer draws a title and subtitle, and the sparkline no longer draws a title. Text drawn inside the svg cannot wrap, clips at the chart's edge and does not follow the page's typography, so these charts now draw only the data. The `customTitle` and `customSubtitle` accessors and the `title` and `subtitle` data fields of the bullet chart are removed, as are the sparkline's `titleText` and `titleTextStyle`. The React `Bullet` and `Sparkline` components drop the matching props.
Put the label in your own markup next to the chart, and give screen readers the chart's name with `a11yTitle`:
```js
// Version 2
bulletChart.customTitle('CPU 1').customSubtitle('GHz');
sparklineChart.titleText('Signups');
// Version 3
//
CPU 1 GHz
above the chart's container
bulletChart.a11yTitle('CPU 1, GHz');
sparklineChart.a11yTitle('Signups');
```
The legend still draws its own labels.
15. Load one bundle instead of a file per chart
Version 2 published a UMD file for each chart, like `britecharts/dist/umd/bar.min.js`. Version 3 publishes one UMD bundle and one CDN bundle with every chart, and ES modules for bundlers. Bundlers keep only the charts you import, so a per-chart file saves nothing there. On a page with a script tag, load the CDN bundle, which includes d3, and use the `core` global:
```html
```
The colors come with the bundle as `core.colors`. The per-chart stylesheets under `dist/styles/charts/` are still published. `@britecharts/wrappers` and `@britecharts/react` also publish only their bundles: import the wrappers and components from the package, or use the `wrappers` and `react` globals.
The packages are ES modules (`"type": "module"`), so they load with `import` in Node as well as in bundlers. `require` still works and gets the CommonJS bundle, which is now a `.cjs` file. If you required a bundle by its path, update the extension: `@britecharts/core/dist/umd/bundle/core.bundled.min.js` is now `core.bundled.min.cjs`, and likewise for `wrappers` and `react`. The CDN bundle keeps its `.js` name.
16. Expect `null` from an accessor you have not set
An accessor that has not been set now reads `null` on every chart. Before, the same accessor read `null` on some charts and `undefined` on others: `yAxisLabel` on the grouped bar, stacked bar, scatter plot and stacked area, `xAxisLabel` on the scatter plot, `numberFormat` on the donut, line and stacked area, and `locale` on the line, stacked area and tooltip.
A truthiness check works as before. Update code that compares with `=== undefined`, and TypeScript code that annotated the old type: the getters are typed `T | null`.
```js
// Version 2
if (lineChart.numberFormat() === undefined) { /* ... */ }
// Version 3
if (lineChart.numberFormat() === null) { /* ... */ }
```
17. Name your data's keys as the charts expect
The accessors that let a chart read its data under other keys are removed: `nameLabel` and `valueLabel` on the bar chart, `groupLabel`, `nameLabel` and `valueLabel` on the grouped bar, `stackLabel`, `nameLabel` and `valueLabel` on the stacked bar, `dateLabel`, `topicLabel` and `valueLabel` on the line chart, `dateLabel`, `keyLabel` and `valueLabel` on the stacked area, and `dateLabel` and `valueLabel` on the sparkline. They warned that they were deprecated since version 2. The React components drop the matching props.
If you used them, rename the keys in your data to the ones each chart's data shape names, such as `name` and `value` for the bar chart:
```js
// Version 2
barChart.nameLabel('letter').valueLabel('frequency');
barContainer.datum([{ letter: 'A', frequency: 0.08 }]).call(barChart);
// Version 3
const data = rows.map(({ letter, frequency }) => ({ name: letter, value: frequency }));
barChart.render(barContainer, data);
```
The tooltip keeps its `dateLabel`, `nameLabel`, `topicLabel` and `valueLabel`: it reads the data points of several charts, and they use different keys.
### New features
1. Start using TypeScript with Britecharts.
You can now use Britecharts in your TypeScript projects! The packages are written in TypeScript, and their type declarations are generated from that source, so they always match what the charts do. Import the types from the package root: each chart's data shape and module type from `@britecharts/core`, and each component's props from `@britecharts/react`.
2. Stop re-rendering charts when the viewport width changes.
In version 2 and our demos, we recommended listening to viewport width changes and re-render charts with the updated container width. This wasn't necessary, as SVGs provide a viewBox property that allows us to make our charts fully responsive out of the box. That's how Britecharts works starting version 3, so say bye-bye to those window 'resize' listeners!
3. Use 'colorMap' to select the colors you want for each data category.
One common request of our users was to specify the colors for each category on the different Britecharts components. Now you can! Use the ["colorMap"](https://britecharts.github.io/britecharts/docs/API/bar#module_Bar--exports.colorMap) property to specify a hash map between category names and HEX colors.
4. Specify the duration of animations with 'animationDuration'
Most Britecharts' components have animations that you can activate with the 'isAnimated' configuration. Since version 3, you can also set the duration of those animations in milliseconds with the 'animationDuration' accessor.
5. Rely on one tooltip for every chart
`tooltip` renders the line, stacked area, stacked bar and grouped bar charts' lists and the bar, scatter plot, heatmap and donut charts' single values; `maxEntries` caps the rows, `layout` forces a layout, `xAxisValueType('category')` shows a category key as it is. `customClick` on the stacked and grouped bar charts carries the clicked bar's own data as a third argument.
6. Chart negative values
The bar, grouped bar, stacked bar and brush charts draw negative values, below or to the left of a zero baseline. They used to throw on a negative datum. The scatter plot's value axis now runs below zero when the data does, and each circle's size shows the magnitude of its value. Before, points with a negative value were not drawn.
7. Show a loading state on every chart
`isLoading` now covers every data chart, including the bullet, heatmap and scatter plot, each with a skeleton in its own shape.
8. Name your charts for screen readers
Every chart gives its svg a role and an accessible name, so a screen reader announces it as an image called, for example, "Bar chart". Set `a11yTitle` to name it after what it shows, and `a11yDescription` to add a sentence that screen readers read after the name. The React components take both as props.
```js
barChart
.a11yTitle('Monthly visits')
.a11yDescription('Visits doubled in May');
```
9. Draw charts with 'render', and give them a 'tooltip'
`render` draws a chart into a CSS selector, an element or a d3 selection, so a page needs no d3 code of its own. The `tooltip` setting connects and places a tooltip, and sets the labels the chart's data points need. Your version 2 code, `container.datum(data).call(chart)` and the tooltip wired by hand, keeps working.
```js
// Version 2
barChart
.on('customMouseOver', chartTooltip.show)
.on('customMouseMove', chartTooltip.update)
.on('customMouseOut', chartTooltip.hide);
barContainer.datum(data).call(barChart);
barContainer.select('.metadata-group').datum([]).call(chartTooltip);
// Version 3
barChart.tooltip(tooltip()).render(barContainer, data);
```
## Summary of Changes
We changed many things in the third version of Britecharts; here are some summaries:
### Breaking Changes
* New monorepo organization of the code with `@britecharts/core` and `@britecharts/react` as the main packages.
* The builds target ES2020 instead of ES5.
* Runs on the d3 v7 modules; negative numbers render with the typographic minus sign.
* Removes the Step chart from every package.
* Removes the line chart's 'dataByTopic' data shape.
* Publishes one UMD bundle and one CDN bundle instead of a UMD file per chart. The per-chart stylesheets stay.
* The packages are ES modules: `import` works in Node, and the CommonJS bundles `require` loads end in `.cjs`.
* Removes the data-key accessors ('nameLabel', 'valueLabel', 'dateLabel', 'topicLabel', 'keyLabel', 'groupLabel', 'stackLabel') from the bar, grouped bar, stacked bar, line, stacked area and sparkline charts, and the matching React props. The tooltip keeps its own.
* An accessor that has not been set reads `null` on every chart, never `undefined`.
* Removes the bullet chart's title and subtitle ('customTitle', 'customSubtitle' and the 'title' and 'subtitle' data fields) and the sparkline's title ('titleText', 'titleTextStyle'), with the matching React props.
* Changes 'loadingMarkup' option into an explicit option for 'isLoading' in most of the charts.
* Adds 'valueLocale' or renames 'locale' into 'valueLocale' for formatting values in the bar chart, grouped bar chart, scatter plot, and stacked bar.
* Fixes the custom format feature in the line and stacked area chart, renaming 'xAxisFormat' into 'xAxisCustomFormat' and 'xAxisCustomFormat' into 'xAxisFormat'. The time combinations are exported as `constants.axisTimeCombinations`.
* Renames value formatting functions into 'numberFormat' in the grouped bar and stacked bar charts.
* Removed the 'aspectRatio' configuration chart from the line, scatter plot, stacked area, bullet, grouped bar, stacked bar.
* Changed 'exportChart' to return a promise.
* The line, stacked area, stacked bar and grouped bar charts dispatch 'customMouseMove' as `(dataPoint, [x, y], [width, height], colorMap)`, the same payload as every other chart; `tooltip.update` still accepts the old `(dataPoint, colorMap, x, y)` order and warns once. React's `Tooltip` passes the new order to its 'customMouseMove' callback.
* The tooltip's 'tooltipOffset' defaults to `{ x: 0, y: 0 }` and 'xAxisValueType' to 'auto'.
* The stacked and grouped bar charts show the tooltip, and dispatch 'customClick', only over a bar.
* React: the components are function components, need React 16.8 or later, redraw only when their props change, and pass `false`, `0` and `''` on to the chart. PropTypes, `StackedBar`'s `nameLabelFormat` prop and the `axisTimeCombinations` prop are removed.
### New Feature Changes
* Written in TypeScript, with type declarations generated from the source
* Negative values in the bar, grouped bar, stacked bar, brush and scatter plot charts
* Loading states on every data chart, including the bullet, heatmap and scatter plot
* Accessible names for every chart, set with 'a11yTitle' and 'a11yDescription'
* Theming with CSS custom properties, and dark mode that follows the page's `color-scheme`
* A `ScatterPlot` component in `@britecharts/react`
* `Brush` and `Heatmap` components in `@britecharts/react`, and `BrushWrapper` and `HeatmapWrapper` in `@britecharts/wrappers`, so every chart has both
* Charts are responsive by default using the viewBox property.
* Adds colorMap to all charts
* Adds 'animationDuration' option to all animated charts
* Added grid helper on charts
* Adds zoom controls for scatter plot
* Added hasMinimumValueScale parameter to autoscale Line Chart y-axis
* Rework of Line Chart animation for better performance
* Allows brush to have missing data and to be animated
* Allows for a fixed window in brush chart with 'isLocked' option
* Added Donut's hasCenterLegend to hide/show center legend
* Added Stacked Area loading state
* Added tooltip on the heatmap
* One tooltip component for every chart: 'tooltip' renders a list or a single value by the data's shape ('layout' forces one), 'miniTooltip' is its single-value preset, and React's 'Tooltip' wraps the bar, scatter plot and heatmap charts too
* The tooltip keeps itself inside the chart (flips and slides at the edges), follows the pointer, fades in and out and eases towards each position, and updates its rows in place
* Tooltip: 'xAxisValueType' gains 'category' and 'auto', 'maxEntries' caps the rows with a "+n more" row, 'show' takes the hovered point
* The stacked and grouped bar charts' 'customClick' carries the clicked bar's data
### Bug Fixes
* Fixes all critical security warnings due to dependencies
* Fixes step chart loading
* Mitigates the stacked and grouped bar charts tooltip issues
* Tooltips no longer get cut off at the chart's edges, wobble across close data points, blink when crossing bars, or catch the pointer; the scatter plot's sits beside its point and a category key no longer titles it "NaN"
* Improved Grouped bar chart animation
* Line chart animation fix on multiline
* Ordering of the horizontal bar chart elements
* Cleans up custom lines annotation text before rendering
* Fixes bullet chart issues
* The scatter plot's trendline starts at the right height
* The brush chart honours 'locale', and the stacked area chart honours 'numberFormat'
* React: unmounting one responsive container no longer stops resizing for the others, and a chart is not drawn twice under StrictMode
* Tooltip tweaks
*Visual Fixes Summary*
* Added extended line on brush chart
* Extended line color matching ticks
* Normalized text sizes in line and stacked area charts
### Contributor's Developer Experience Changes
* Deprecated Travis into Github Actions
* Moved the tests from Karma to Vitest
* Moved from Yarn to pnpm, and the build from webpack to Vite
* Rewrote the packages in TypeScript, type-checked in CI
* Integration tests install the packed packages into vanilla, TypeScript and React projects
* Added linting and formatting for CSS and JS
* Changed organization of tests and data builders to be colocated
---
# @britecharts/core
Source: https://britecharts.github.io/britecharts/docs/packages/core-readme
> `@britecharts/core` is the main package for the [Britecharts][homepage] charting library. Use this package directly in your JavaScript projects.
## Usage
Read the [main readme][readme] or check the [Getting Started guide][gettingStarted] to learn how to use Britecharts.
## Installation
To install run:
```sh
pnpm add @britecharts/core
```
Or, with npm:
```
npm i --save @britecharts/core
```
Britecharts is available as an [NPM module][npmModule] or through CDN links (in [different formats][jsDelivrLib] or a [bundle][jsDelivrDist]).
## Using Britecharts with a coding agent
The package ships an agent skill in `skills/britecharts`. It covers each chart's data shape and accessors, tooltip wiring, React and the wrappers, and the v2 code that no longer works in v3. Install it with the [skills CLI][skillsCli]:
```sh
npx skills add britecharts/britecharts
```
Or copy `node_modules/@britecharts/core/skills/britecharts` into your agent's skills folder, such as `.claude/skills/` for Claude Code. Agents that read [llms.txt][llmsTxt] can also load the whole documentation from [llms-full.txt][llmsFullTxt].
## See Also
- [Documentation Homepage][homepage]
- [Contributing Guide][contributing]
- [Code of Conduct][codeOfConduct]
## Contribute
Check the [contributing guide][contributing] if you want to help us bringing these in.
[readme]: https://britecharts.github.io/britecharts/docs/Britecharts
[homepage]: https://britecharts.github.io/britecharts/
[gettingStarted]: https://britecharts.github.io/britecharts/docs/tutorials/getting-started
[npmModule]: https://www.npmjs.com/package/@britecharts/core
[jsDelivrLib]: https://cdn.jsdelivr.net/npm/@britecharts/core/dist/
[jsDelivrDist]: https://cdn.jsdelivr.net/npm/@britecharts/core/dist/cdn/bundle/core.cdn.min.js
[skillsCli]: https://github.com/vercel-labs/skills
[llmsTxt]: https://britecharts.github.io/britecharts/llms.txt
[llmsFullTxt]: https://britecharts.github.io/britecharts/llms-full.txt
[contributing]: https://github.com/britecharts/britecharts/blob/main/.github/CONTRIBUTING.md
[codeOfConduct]: https://github.com/britecharts/britecharts/blob/main/CODE_OF_CONDUCT.md
---
# @britecharts/wrappers
Source: https://britecharts.github.io/britecharts/docs/packages/wrappers-readme
> `@britecharts/wrappers` is a package that simplifies the use of [Britecharts'][britecharts] components with frontend frameworks.
## Usage
`@britecharts/wrappers` components expose a simple API to allow its use in frontend frameworks. This API contains three methods: `create`, `update`, and `destroy`.
To use them, you will pass a configuration object following the Britecharts core component API and a container:
```js
import { BarWrapper } from '@britecharts/wrappers';
const container = document.querySelector('.container');
const data = [
{
name: 'Vibrant',
value: 2,
},
{
name: 'Opalescent',
value: 4,
},
{
name: 'Shining',
value: 3,
},
];
const configuration = {
width: 400,
margin: {left: 10},
};
const barInstance = BarWrapper.create(container, data, configuration);
//...
BarWrapper.update(container, newData, {}, barInstance);
```
The wrappers include a lightweight configuration and container validation.
A configuration value of `undefined` or `null` means "not set" and the chart keeps its own default. Any other value is applied, including the falsy ones: `false`, `0` and `''` reach the chart, so a setting can be turned back off with `{ isLoading: false }`.
In theory, you shouldn't be using this wrappers by themselves, but you might prefer this API (more OO-like) for your vanilla JavaScript projects.
## API
The API of the wrappers has only three methods: `create`, `update` and `destroy`. Note that each component wrapper's configuration options is a reflection of [Britecharts][britecharts-api] charts' APIs.
### Create
Creates a new Britechart chart and returns its instance.
Signature:
`.create(HTMLElement, , ) => BritechartChart`
Example:
```js
const barInstance = BarWrapper.create(container, data, configuration);
```
### Update
Updates a chart with new data or configuration.
Signature:
`.update(HTMLElement, , , BritechartChart) => BritechartChart`
Example:
```js
BarWrapper.update(container, newData, {}, barInstance);
```
### Destroy
Removes the chart's `svg` from the container, so the container can be used again (a `create` after a `destroy` draws exactly one chart). It only removes that `svg`: never the container itself, which a framework may own, nor anything else inside it.
Signature:
`.destroy(HTMLElement) => void`
Example:
```js
BarWrapper.destroy(container);
```
`TooltipWrapper.destroy` has its own contract: it removes the tooltip from inside the element and never an `svg`, because a tooltip is created inside the chart it decorates and destroyed against the element around it.
### Validation
`create` and `update` check the configuration before drawing, and throw an error that says what to fix: a key the chart has no accessor for, with the nearest one it does have, and a value of the wrong type, with the type it should be.
```
Value not supported by Britechart: height chartGradient
height: expected a number, got the string "300"
chartGradient: expected an array of 2 strings, got an array of 1
Supported accessors: https://britecharts.github.io/britecharts/docs/API/bar
```
An `undefined` or `null` value is skipped, and the chart keeps its default.
### Chart specs and their JSON Schemas
A chart can be written down as a spec: its name, its configuration and its data. Each chart has a JSON Schema for its spec, generated from the TypeScript types the wrappers take, so editors and coding agents can check a spec, and complete it, without running it:
```json
{
"$schema": "https://britecharts.github.io/britecharts/schema/v3/bar.json",
"chart": "bar",
"config": { "isHorizontal": true, "a11yTitle": "Signups by plan" },
"data": [{ "name": "Pro", "value": 412 }]
}
```
The schemas are published at `https://britecharts.github.io/britecharts/schema/v3/.json` and ship in this package as `@britecharts/wrappers/schemas/.json`, one per chart, named as core names it (`bar`, `groupedBar`, `scatterPlot`…). Draw a spec with its wrapper: `BarWrapper.create(element, spec.data, spec.config)`. Options that take a function, such as the events and the formatting functions, can't be written in JSON; set them from JavaScript.
## Availability
Every chart in `@britecharts/core` has a wrapper: `BarWrapper`, `BrushWrapper`, `BulletWrapper`, `DonutWrapper`, `GroupedBarWrapper`, `HeatmapWrapper`, `LegendWrapper`, `LineWrapper`, `ScatterPlotWrapper`, `SparklineWrapper`, `StackedAreaWrapper`, `StackedBarWrapper` and `TreemapWrapper`, plus `TooltipWrapper` for the tooltip.
## Installation
To install run:
```
pnpm add @britecharts/core @britecharts/wrappers
```
Or, with npm:
```
npm i --save @britecharts/core @britecharts/wrappers
```
### Roadmap
Our idea for the short term is to update this package to use TypeScript natively. [Let us know][d3Slack] if you want to help with it.
[britecharts]: https://github.com/britecharts/
[britecharts-api]: https://britecharts.github.io/britecharts/docs/Britecharts
[d3Slack]: https://d3js.slack.com/
---
# @britecharts/react
Source: https://britecharts.github.io/britecharts/docs/packages/react-readme
> `@britecharts/react` is a package that allows you use [Britecharts][britecharts] within [React][react] applications.
## Usage
Every chart in `@britecharts/react` is a function component: you pass in some props, and it renders a chart.
```jsx
import { Bar } from '@britecharts/react';
const data = [
{
name: 'Vibrant',
value: 2,
},
{
name: 'Opalescent',
value: 4,
},
{
name: 'Shining',
value: 3,
},
];
```
Check our [Storybook][storybook] for more examples and check the source to copy/paste code.
### Loading data
`data` is required. Pass `null` while it loads: nothing is drawn until it arrives, and the chart is drawn as soon as it does. Leaving `data` out, or passing `undefined`, is an error (and a type error, too).
```jsx
```
### Updating a chart
A chart is redrawn when its props change, and only then. On every render the data and each configuration value are compared with what was last drawn, so a re-render with the same props costs nothing. The consequence is that **the data has to be a new array or object to be redrawn**: mutating it in place and re-rendering with the same reference does nothing.
```jsx
setData([...data, newPoint]); // redraws
data.push(newPoint);
setData(data); // does not: same array, nothing changed
```
### No instance, no ref
Function components have no instance to point a `ref` at, so a `ref` on a chart is not accepted (the typings say so). A chart is drawn into a `
` the component owns, and removes what it drew when it unmounts.
### Tooltips
A `Tooltip` wraps the chart it decorates: give it a `render` prop that returns the chart, and pass on the props it hands you, which are what connect the two.
The charts name the fields of their data points differently, so some of them need the tooltip told where to look:
| Chart | `Tooltip` props |
| --- | --- |
| `Line` | `topicLabel="topics"` |
| `StackedArea` | none |
| `StackedBar` | `nameLabel="stack"` |
| `GroupedBar` | `nameLabel="group"` |
| `ScatterPlot` | `valueLabel="y"` |
| `Bar`, `Donut`, `Heatmap`, `Treemap` | none |
Without them, the tooltip shows no rows (line), rows without their colours (stacked and grouped bar) or no value (scatter plot).
```jsx
import { Line, Tooltip } from '@britecharts/react';
}
topicLabel="topics"
title="A title"
/>
```
### Responsive charts
`ResponsiveContainer` hands its `render` prop the width it has measured, and measures again when the window is resized. `withResponsiveness` does the same for a component you wrap, as its `width` prop (a `width` you pass yourself wins).
```jsx
import { Line, ResponsiveContainer, withResponsiveness } from '@britecharts/react';
}
/>
const ResponsiveLine = withResponsiveness(Line);
```
## API
Each component's API is a reflection of [Britecharts][britecharts] charts and their APIs. They also have a bunch of React specific props, and there are some changes due to the declarative way of building with React.
For example, if we need to check the options of a bar chart, you will first check the [bar chart's API][barChartAPI] in the main project API reference page.
Every Britecharts chart has a component:
- Bar charts [(API)][barChartAPI]
- Brush charts [(API)][brushAPI]
- Bullet charts [(API)][bulletAPI]
- Grouped Bar charts [(API)][groupedBarChartAPI]
- Donut charts [(API)][donutChartAPI]
- Heatmaps [(API)][heatmapAPI]
- Treemaps [(API)][treemapAPI]
- Line charts [(API)][lineChartAPI]
- Scatter Plots [(API)][scatterPlotAPI]
- Sparkline charts [(API)][sparklineChartAPI]
- Stacked Area charts [(API)][stackedAreaChartAPI]
- Stacked Bar charts [(API)][stackedBarChartAPI]
- Tooltips [(API)][tooltipAPI], wrapping the line, stacked area, stacked bar and grouped bar charts with a list of values, and the bar, scatter plot and heatmap charts with a single value (the mini tooltip)
- Legends [(API)][legendAPI]
- The `ResponsiveContainer` component and the `withResponsiveness` function, described above
These components were previously hosted in the [britecharts-react][britecharts-react] repository, but became a package with Britecharts V3.
## Installation
To install run:
```
pnpm add @britecharts/core @britecharts/wrappers @britecharts/react
```
Or, with npm:
```
npm i --save @britecharts/core @britecharts/wrappers @britecharts/react
```
Britecharts-React is available as an [NPM module][npmModule] or through CDN links (in [different formats][jsDelivrLib] or a [bundle][jsDelivrDist]).
Import the components from the package: bundlers get ES modules, and `require('@britecharts/react')` gets the UMD bundle. The [React consumer][testProject] in the integration package shows every way of loading it, and is what CI runs.
### Supported React versions
`peerDependencies` requires `react` and `react-dom` `>=16.8`: the components use hooks, which arrived in that release. What is actually verified on every commit:
- **React 19**, by the unit tests, which now run on React Testing Library, and in a real browser: CI packs the package the way a release does, installs it into a React 19 project, and loads it in production and in a development build under `StrictMode`, which runs every effect's setup, cleanup and setup again.
React 17 and 18 are expected to work and are not exercised. If you hit a version-specific problem on an older React, please open an issue.
## Acknowledgments
For this project, we have followed the approach called ‘Mapping Lifecycle methods’ based on [Nicholas Hery's article][integration-article]: a chart's `create`, `update` and `destroy` are called from the component's mount, update and unmount, which one internal hook now does for every chart. We want to recognize all the contributors in the parent project [Britecharts][britecharts].
## See Also
- [Documentation Homepage][homepage]
- [Contributing Guide][contributing]
- [Code of Conduct][codeOfConduct]
## Contribute
When Britecharts adds a chart, check out our [how-to guide for creating new charts][howtoCreate] to bring it to React. Check also the [contributing guide][contributing] if you want to help.
Note that the aim of this project is to allow the usage of Britecharts within your React applications. For that, we are ‘wrapping’ Britecharts with `@britecharts/wrappers`. This means that **any new features need to first be implemented on Britecharts**. Only then you could update the props and logic that passes in the configuration.
### TypeScript
The package is written in TypeScript, and its type declarations are generated from the components at build time. Each component's props type is exported from the package root (`BarChartProps`, `LineProps` and so on), and CI compiles a TypeScript project against the packed package.
[react]: https://react.dev/
[integration-article]: http://nicolashery.com/integrating-d3js-visualizations-in-a-react-app/
[storybook]: https://britecharts.github.io/britecharts/storybook/react/
[barChartAPI]: https://britecharts.github.io/britecharts/docs/API/bar
[groupedBarChartAPI]: https://britecharts.github.io/britecharts/docs/API/grouped-bar
[donutChartAPI]: https://britecharts.github.io/britecharts/docs/API/donut
[lineChartAPI]: https://britecharts.github.io/britecharts/docs/API/line
[scatterPlotAPI]: https://britecharts.github.io/britecharts/docs/API/scatter-plot
[sparklineChartAPI]: https://britecharts.github.io/britecharts/docs/API/sparkline
[stackedAreaChartAPI]: https://britecharts.github.io/britecharts/docs/API/stacked-area
[stackedBarChartAPI]: https://britecharts.github.io/britecharts/docs/API/stacked-bar
[tooltipAPI]: https://britecharts.github.io/britecharts/docs/API/tooltip
[legendAPI]: https://britecharts.github.io/britecharts/docs/API/legend
[bulletAPI]: https://britecharts.github.io/britecharts/docs/API/bullet
[brushAPI]: https://britecharts.github.io/britecharts/docs/API/brush
[heatmapAPI]: https://britecharts.github.io/britecharts/docs/API/heatmap
[treemapAPI]: https://britecharts.github.io/britecharts/docs/API/treemap
[jsDelivrLib]: https://cdn.jsdelivr.net/npm/britecharts-react@latest/lib/
[jsDelivrDist]: https://cdn.jsdelivr.net/npm/britecharts-react@latest/dist/
[npmModule]: https://www.npmjs.com/package/britecharts-react
[contributing]: https://github.com/britecharts/britecharts/blob/main/.github/CONTRIBUTING.md
[codeOfConduct]: https://github.com/britecharts/britecharts/blob/main/CODE_OF_CONDUCT.md
[homepage]: https://britecharts.github.io/britecharts/
[britecharts]: https://britecharts.github.io/britecharts/
[testProject]: https://github.com/britecharts/britecharts/tree/main/packages/integration/consumers/react
[howtoCreate]: https://github.com/britecharts/britecharts-react/blob/master/CONTRIBUTING.md#creating-a-new-chart
[britecharts-react]: https://github.com/britecharts/britecharts-react/
---
# Bar
Source: https://britecharts.github.io/britecharts/docs/API/bar
Bar Chart reusable API class that renders a
simple and configurable bar chart.
**Example**
```js
import { bar } from '@britecharts/core';
// dataset: [{ name, value }]
const barChart = bar();
barChart
.height(500)
.width(800)
.render('.css-selector', dataset);
```
* ~~.enableLabels([_x]) ⇒ `Boolean` \| `module`~~
## bar(_selection, _data)
This function creates the graph using the selection as container
**Kind**: Exported function
| Param | Type | Description |
| --- | --- | --- |
| _selection | `D3Selection` | A d3 selection that represents the container(s) where the chart(s) will be rendered |
| _data | `BarChartData` | The data to attach and generate the chart |
## a11yTitle(_x) ⇒ `String` \| `null` \| `module`
Gets or Sets the name screen readers announce for the chart. It is
set as the svg's `aria-label`. Unset, the chart is announced as
"Bar chart".
**Kind**: method of `bar`
**Returns**: `String` \| `null` \| `module` - Current a11yTitle or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `String` \| `null` | Desired accessible title for the chart |
## a11yDescription(_x) ⇒ `String` \| `null` \| `module`
Gets or Sets a longer description screen readers announce after the
chart's name, such as what the data shows. It is rendered as the svg's
``. Unset, the chart has no description.
**Kind**: method of `bar`
**Returns**: `String` \| `null` \| `module` - Current a11yDescription or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `String` \| `null` | Desired accessible description for the chart |
## a11yDataTable(_x) ⇒ `Boolean` \| `module`
Gets or Sets whether the chart renders its data as a visually hidden
table after its svg, which screen readers can read cell by cell. On by
default; set it to false when the app gives the data its own accessible
form.
**Kind**: method of `bar`
**Returns**: `Boolean` \| `module` - Current a11yDataTable or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `Boolean` | Whether to render the data table |
## a11yKeyboardNavigation(_x) ⇒ `Boolean` \| `module`
Gets or Sets whether a keyboard can move through the chart's data
points: the chart takes one tab stop, the arrow keys move between
points, Home and End go to the first and last, and Escape lets go. The
tooltip and highlights follow focus as they follow the pointer. On by
default.
**Kind**: method of `bar`
**Returns**: `Boolean` \| `module` - Current a11yKeyboardNavigation or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `Boolean` | Whether the keyboard can move through the data |
## animationDuration(_x) ⇒ `duration` \| `module`
Gets or Sets the duration of the animation
**Kind**: method of `bar`
**Returns**: `duration` \| `module` - Current animation duration or Chart module to chain calls
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| _x | `Number` | `1200` | Desired animation duration for the graph |
## betweenBarsPadding(_x) ⇒ `padding` \| `module`
Gets or Sets the padding of the chart (Default is 0.1)
**Kind**: method of `bar`
**Returns**: `padding` \| `module` - Current padding or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `Number` \| `module` | Padding value to get/set |
## chartGradient(_x) ⇒ `Array.` \| `module`
Gets or Sets the gradient colors of a bar in the chart
**Kind**: method of `bar`
**Returns**: `Array.` \| `module` - Current color gradient or Line Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `Array.` | Desired color gradient for the line (array of two hexadecimal numbers) |
## colorMap([_x]) ⇒ `object` \| `module`
Gets or Sets the colorMap of the chart
**Kind**: method of `bar`
**Returns**: `object` \| `module` - Current colorMap or Chart module to chain calls
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [_x] | `object` | `` | Color map |
**Example**
```js
barChart.colorMap({name: 'colorHex', name2: 'colorString'})
```
## colorSchema(_x) ⇒ `colorSchema` \| `module`
Gets or Sets the colorSchema of the chart
**Kind**: method of `bar`
**Returns**: `colorSchema` \| `module` - Current colorSchema or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `Array.` | Desired colorSchema for the graph |
## ~~enableLabels([_x]) ⇒ `Boolean` \| `module`~~
***Use `hasLabels`, which does the same. Goes in version 4.***
If true, adds labels at the end of the bars
**Kind**: method of `bar`
**Returns**: `Boolean` \| `module` - Current value of hasLabels or Chart module to chain calls
| Param | Type | Default |
| --- | --- | --- |
| [_x] | `Boolean` | `false` |
## exportChart(filename, title) ⇒ `Promise`
Exports the chart and fires a download: an svg file when the filename
ends in `.svg`, and a png otherwise
**Kind**: method of `bar`
**Returns**: `Promise` - Promise that resolves if the chart image was loaded and downloaded successfully
| Param | Type | Description |
| --- | --- | --- |
| filename | `String` | Name of the downloaded file, whose extension picks the format |
| title | `String` | Title to add at the top of the exported picture |
## hasLabels([_x]) ⇒ `Boolean` \| `module`
If true, adds labels at the end of the bars
**Kind**: method of `bar`
**Returns**: `Boolean` \| `module` - Current value of hasLabels or Chart module to chain calls
| Param | Type | Default |
| --- | --- | --- |
| [_x] | `Boolean` | `false` |
## hasPercentage(_x) ⇒ `boolean` \| `module`
Gets or Sets the hasPercentage status
**Kind**: method of `bar`
**Returns**: `boolean` \| `module` - Is percentage used or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `boolean` | Should use percentage as value format |
## hasSingleBarHighlight(_x) ⇒ `boolean` \| `module`
Gets or Sets the hasSingleBarHighlight status.
If the value is true (default), only the hovered bar is considered to
be highlighted and will be darkened by default. If the value is false,
all the bars but the hovered bar are considered to be highlighted
and will be darkened (by default). To customize the bar highlight or
remove it completely, use highlightBarFunction instead.
**Kind**: method of `bar`
**Returns**: `boolean` \| `module` - Is hasSingleBarHighlight used or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `boolean` | Should highlight the hovered bar |
## height(_x) ⇒ `height` \| `module`
Gets or Sets the height of the chart
**Kind**: method of `bar`
**Returns**: `height` \| `module` - Current height or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `number` | Desired width for the graph |
## highlightBarFunction(_x) ⇒ `highlightBarFunction` \| `module`
Gets or Sets the highlightBarFunction function. The callback passed to
this function returns a bar selection from the bar chart. Use this function
if you want to apply a custom behavior to the highlighted bar on hover.
When hasSingleBarHighlight is true the highlighted bar will be the
one that was hovered by the user. When hasSingleBarHighlight is false
the highlighted bars are all the bars but the hovered one. The default
highlight effect on a bar is darkening the highlighted bar(s) color.
**Kind**: method of `bar`
**Returns**: `highlightBarFunction` \| `module` - Is highlightBarFunction used or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `function` | Desired operation operation on a hovered bar passed through callback |
**Example**
```js
barChart.highlightBarFunction(bar => bar.attr('fill', 'blue'))
barChart.highlightBarFunction(null) // will disable the default highlight effect
```
## isAnimated(_x) ⇒ `isAnimated` \| `module`
Gets or Sets the isAnimated property of the chart, making it to animate when render.
The chart draws without animation when the reader's system asks for
reduced motion (`prefers-reduced-motion`), whatever this is set to.
By default this is 'false'
**Kind**: method of `bar`
**Returns**: `isAnimated` \| `module` - Current isAnimated flag or Chart module
| Param | Type | Description |
| --- | --- | --- |
| _x | `Boolean` | Desired animation flag |
## isHorizontal(_x) ⇒ `isHorizontal` \| `module`
Gets or Sets the horizontal direction of the chart
**Kind**: method of `bar`
**Returns**: `isHorizontal` \| `module` - If it is horizontal or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `number` | Desired horizontal direction for the graph |
## labelsMargin([_x]) ⇒ `number` \| `module`
Offset between end of bar and start of the percentage bars
**Kind**: method of `bar`
**Returns**: `number` \| `module` - Current offset or Chart module to chain calls
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [_x] | `number` | `7` | Margin offset from end of bar |
## labelsNumberFormat([_x]) ⇒ `string` \| `module`
Gets or Sets the labels number format
**Kind**: method of `bar`
**Returns**: `string` \| `module` - Current labelsNumberFormat or Chart module to chain calls
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [_x] | `string` | `"\",f\""` | desired label number format for the bar chart |
## labelsSize([_x]) ⇒ `number` \| `module`
Get or Sets the labels text size
**Kind**: method of `bar`
**Returns**: `number` \| `module` - Current text size or Chart module to chain calls
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [_x] | `number` | `12` | label font size |
## isLoading(flag) ⇒ `boolean` \| `module`
Gets or Sets the loading state of the chart
**Kind**: method of `bar`
**Returns**: `boolean` \| `module` - Current loading state flag or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| flag | `boolean` | Desired value for the loading state |
## margin(_x) ⇒ `margin` \| `module`
Gets or Sets the margin of the chart
**Kind**: method of `bar`
**Returns**: `margin` \| `module` - Current margin or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `object` | Margin object to get/set |
## numberFormat(_x) ⇒ `string` \| `module`
Gets or Sets the number format of the bar chart
**Kind**: method of `bar`
**Returns**: `string` \| `module` - Current numberFormat or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `string` | = ',f' Desired numberFormat for the chart. See examples [here](https://d3js.org/d3-format) |
## on() ⇒ `module`
Exposes an 'on' method that acts as a bridge with the event dispatcher
We are going to expose this events:
customMouseOver, customMouseMove, customMouseOut, and customClick
**Kind**: method of `bar`
**Returns**: `module` - Bar Chart
## percentageAxisToMaxRatio(_x) ⇒ `ratio` \| `module`
Configurable extension of the x axis. If your max point was 50% you might want to show x axis to 60%, pass 1.2
**Kind**: method of `bar`
**Returns**: `ratio` \| `module` - Current ratio or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `number` | ratio to max data point to add to the x axis |
## shouldReverseColorList(_x) ⇒ `boolean` \| `module`
Gets or Sets whether the color list should be reversed or not
**Kind**: method of `bar`
**Returns**: `boolean` \| `module` - Is color list being reversed or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `boolean` | Should reverse the color list |
## orderingFunction(_x) ⇒ `function` \| `Module`
Changes the order of items given the custom function
**Kind**: method of `bar`
**Returns**: `function` \| `Module` - A custom ordering function or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `function` | A custom function that sets logic for ordering |
## valueLocale([_x]) ⇒ `LocaleObject` \| `module`
Gets or Sets the locale which our formatting functions use.
Check [the d3-format docs](https://github.com/d3/d3-format#formatLocale) for the required values.
**Kind**: method of `bar`
**Returns**: `LocaleObject` \| `module` - Current locale object or Chart module to chain calls
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [_x] | `LocaleObject` | `` | _x Desired locale object format. |
**Example**
```js
barChart
.valueLocale({thousands: '.', grouping: [3], currency: ["$", ""], decimal: "."})
```
## width(_x) ⇒ `width` \| `module`
Gets or Sets the width of the chart
**Kind**: method of `bar`
**Returns**: `width` \| `module` - Current width or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `number` | Desired width for the graph |
## xAxisLabel(_x) ⇒ `String` \| `module`
Gets or Sets the text of the xAxisLabel on the chart
**Kind**: method of `bar`
**Returns**: `String` \| `module` - Label or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `String` | Desired text for the label |
## xAxisLabelOffset(_x) ⇒ `Number` \| `module`
Gets or Sets the offset of the xAxisLabel on the chart
**Kind**: method of `bar`
**Returns**: `Number` \| `module` - label or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `Number` | Desired offset for the label |
## xTicks(_x) ⇒ `Number` \| `module`
Gets or Sets the number of ticks of the x axis on the chart
**Kind**: method of `bar`
**Returns**: `Number` \| `module` - Current xTicks or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `Number` | = 5 Desired horizontal ticks |
## yAxisLabel(_x) ⇒ `String` \| `module`
Gets or Sets the text of the yAxisLabel on the chart
**Kind**: method of `bar`
**Returns**: `String` \| `module` - Label or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `String` | Desired text for the label |
## yAxisLabelOffset(_x) ⇒ `Number` \| `module`
Gets or Sets the offset of the yAxisLabel on the chart
**Kind**: method of `bar`
**Returns**: `Number` \| `module` - Label or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `Number` | Desired offset for the label |
## yAxisPaddingBetweenChart(_x) ⇒ `Number` \| `module`
Space between y axis and chart
**Kind**: method of `bar`
**Returns**: `Number` \| `module` - Current value of yAxisPaddingBetweenChart or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `Number` | = 10 Space between y axis and chart |
## yTicks(_x) ⇒ `Number` \| `module`
Gets or Sets the number of vertical ticks on the chart
**Kind**: method of `bar`
**Returns**: `Number` \| `module` - Current yTicks or Chart module to chain calls
| Param | Type | Description |
| --- | --- | --- |
| _x | `Number` | = 6 Desired number of vertical ticks for the graph |
## tooltip(_x) ⇒ `module` \| `null`
Gets or Sets the tooltip the chart shows: a `tooltip()`, set on this
chart only. The chart connects it to its
pointer and keyboard events, draws it in place, and sets the labels its
data points need, unless they were set on the tooltip; it does so now
if the chart has drawn, and again on every draw. Its event handlers go
under the `britechartsTooltip` namespace. Null, or another tooltip,
removes the one it had.
**Kind**: method of `bar`
**Returns**: `module` \| `null` - Current tooltip or Chart module to chain calls
**Throws**:
- `Error` When the tooltip is already set on another chart
| Param | Type | Description |
| --- | --- | --- |
| _x | `module` \| `null` | The tooltip to show |
**Example**
```js
bar().tooltip(tooltip().title('Uses')).render('#chart', data);
```
## render(target, [data]) ⇒ `module`
Draws the chart into a target: a CSS selector, an element or a d3
selection, as `select(target).datum(data).call(chart)` does. A selector
draws into the first element it matches. Without data, the chart
redraws with the data it last drew there.
**Kind**: method of `bar`
**Returns**: `module` - The chart module, to chain calls
**Throws**:
- `Error` When the target matches no element
| Param | Type | Description |
| --- | --- | --- |
| target | `String` \| `Element` \| `D3Selection` | Where to draw the chart |
| [data] | `Object` | The data to draw |
**Example**
```js
bar().width(600).render('#chart', data);
```
## exports~BarChartData : `Array.