Weights
With weights, each bar is the sum of the weights of its values. Use it for survey weights, or for data that comes as value and frequency.
An array of weights
ts
// Weights: each bar is the sum of its values' weights.
import type {ChartConfiguration} from 'chart.js';
const config: ChartConfiguration<'histogram'> = {
type: 'histogram',
data: {
datasets: [
{
label: 'Respondents (weighted)',
// Ages of survey respondents and the sample weight of each one.
data: [23, 25, 31, 34, 35, 41, 44, 47, 52, 58, 61, 67, 70],
weights: [1.4, 1.2, 0.9, 1.1, 0.8, 1, 1.3, 0.7, 1, 0.9, 1.6, 2.1, 1.8],
binWidth: 10,
binStart: 20
}
]
},
options: {
scales: {
x: {title: {display: true, text: 'Age'}},
y: {title: {display: true, text: 'Weighted count'}}
}
}
};
export default config;Weights from object data
With object data, weights can name the key that holds each weight.
ts
// Values and weights read from object data by key.
import type {ChartConfiguration} from 'chart.js';
import {orders} from './data/index.js';
const config: ChartConfiguration<'histogram'> = {
type: 'histogram',
data: {
datasets: [
{
label: 'Orders',
// One entry per order value, with how many orders had it.
data: orders,
parsing: {key: 'value'},
weights: 'orders',
binWidth: 10,
binStart: 0,
backgroundColor: 'rgba(255, 159, 64, 0.7)'
}
]
},
options: {
scales: {
x: {title: {display: true, text: 'Order value (€)'}},
y: {title: {display: true, text: 'Orders'}}
}
}
};
export default config;