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 first.
How to Customize the Chart's Colors
Follow these steps to customize Britecharts' charts to use different color schemas:
- Find out if your chart supports the
.colorSchema()configuration, if so, keep on reading - Check the Color Palettes demo page and find a palette you like
- Import the
colorshelper at the top of your file - Set the color palette with
.colorSchema(colors.colorSchemas.orange)or with any other color schema - Draw the chart
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.
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:
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 Add a Tooltip to a Chart
Every chart dispatches the same three events, and the tooltip has a handler for each:
- Create the tooltip:
tooltip()for the line, stacked area, stacked bar and grouped bar charts, which list one row per topic, orminiTooltip()for the bar, donut, heatmap and scatter plot, which show one value - Connect the chart's
customMouseOver,customMouseMoveandcustomMouseOutevents to the tooltip'sshow,updateandhide - Tell the tooltip where the chart keeps its data, if the table below lists a setting for it
- 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)
const stackedBarChart = stackedBar();
const chartTooltip = tooltip()
.topicLabel('values')
.nameLabel('stack');
stackedBarChart
.on('customMouseOver', chartTooltip.show)
.on('customMouseMove', chartTooltip.update)
.on('customMouseOut', chartTooltip.hide);
select('.js-chart').datum(data).call(stackedBarChart);
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. Without it, 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, donut, 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 describes each setting, and the 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:
numberFormattakes a d3-format specifier, 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 anumberFormatof its own.valueLocaletakes a d3-format locale definition 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 leastdecimal,thousands,groupingandcurrency, or the chart throws.localetakes a language tag such as'fr-FR', and localizes the dates in the tooltip and the brush withIntl.DateTimeFormat.
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:
- Set
isLoading(true)and draw the chart with whatever data you have, even an empty array - When the data arrives, set
isLoading(false)and draw the chart again with it
barChart.isLoading(true);
container.datum([]).call(barChart);
fetchData().then((data) => {
barChart.isLoading(false);
container.datum(data).call(barChart);
});
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):
lineChart.isAnimated(true).animationDuration(600);
animationDuration does nothing while isAnimated is false. The bar, grouped bar, stacked bar, line, stacked area, donut, heatmap, scatter plot, sparkline and brush charts animate. React components take both as props.
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 to change it.
How to Make a Chart Accessible
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:
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.
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:
<h3>CPU load <small>GHz</small></h3>
<div class="js-bullet-chart"></div>
bulletChart.a11yTitle('CPU load, GHz');
select('.js-bullet-chart').datum(data).call(bulletChart);
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:
- Render the chart using the default settings, see if the x-axis format is satisfactory. If not, keep on reading.
- Check the chart's reference to find out the configuration options, for example, the line chart reference
- Check the options within the
axisTimeCombinationsobject 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'
}
- Set the
xAxisFormatparameter to a value from the ones below (except 'custom') - 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.
- Set the
xAxisFormatparameter to the value'custom' - Set the
xAxisCustomFormatparameter to a valid D3.js time format specifier string. For example:line.xAxisCustomFormat('%H') - Play around with different specifiers until finding something that works. You can experiment in this block example.
Remember that for increased accuracy, all date formats in Britecharts should be provided in ISO 8601 Extended Format.