BoxPlot with Points in JavaScript
Using ApexCharts with JavaScript
This BoxPlot with Points example uses ApexCharts.js directly in JavaScript, with no wrapper component.
Install it with npm install apexcharts, then mount the chart with new ApexCharts(element, options).render().
// ── Reproducible synthetic data (seeded PRNG, no network) ──────────────
function mulberry32(a) {
return function () {
a |= 0
a = (a + 0x6d2b79f5) | 0
var t = Math.imul(a ^ (a >>> 15), 1 | a)
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
var rng = mulberry32(13572468)
function gauss(mean, sd) {
var u = 0,
v = 0
while (u === 0) u = rng()
while (v === 0) v = rng()
return mean + sd * Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v)
}
function quantile(sorted, q) {
var pos = (sorted.length - 1) * q
var b = Math.floor(pos)
var r = pos - b
return sorted[b + 1] !== undefined
? sorted[b] + r * (sorted[b + 1] - sorted[b])
: sorted[b]
}
// For each team draw a sample, then derive both the 5-number summary (the box)
// and keep the raw observations (the overlaid points).
function buildBox(name, n, mean, sd) {
var data = []
for (var i = 0; i < n; i++) data.push(Math.round(gauss(mean, sd) * 10) / 10)
var s = data.slice().sort(function (a, b) {
return a - b
})
return {
x: name,
y: [
s[0],
quantile(s, 0.25),
quantile(s, 0.5),
quantile(s, 0.75),
s[s.length - 1],
],
points: data,
}
}
var TEAMS = [
buildBox('Alpha', 40, 72, 6),
buildBox('Bravo', 40, 65, 9),
buildBox('Charlie', 40, 78, 5),
buildBox('Delta', 40, 70, 11),
]
var options = {
series: [
{
name: 'Score',
type: 'boxPlot',
data: TEAMS,
},
],
chart: {
type: 'boxPlot',
height: 460,
},
title: {
text: 'Score distribution by team',
},
plotOptions: {
boxPlot: {
colors: { upper: '#5b8def', lower: '#a3c0f9' },
// overlay each raw observation as a jittered dot
points: { show: true, size: 3, jitter: 0.6 },
},
},
stroke: { colors: ['#37474f'] },
}
var chart = new ApexCharts(document.querySelector('#chart'), options)
chart.render()