|
| 1 | +import { |
| 2 | + createCurvePath, |
| 3 | + createSvg, |
| 4 | + extent, |
| 5 | + getElementFontSize, |
| 6 | + LINE_STROKE_COLOR, |
| 7 | + max, |
| 8 | + mean, |
| 9 | + scaleLinear, |
| 10 | +} from '../utils'; |
| 11 | +import { ticks } from '../utils/scales'; |
| 12 | + |
| 13 | +const KDE_BANDWIDTH = 7; // Controls the smoothness of the KDE plot. |
| 14 | +const TICK_COUNT = 40; // Number of points to sample for the density estimation. |
| 15 | + |
| 16 | +export interface DistributionConfig { |
| 17 | + data: number[]; |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * |
| 22 | + * @param container |
| 23 | + * @param config |
| 24 | + */ |
| 25 | +export const renderDistribution = (container: Element, config: DistributionConfig) => { |
| 26 | + const { data } = config; |
| 27 | + |
| 28 | + function kernelDensityEstimator(kernel: (v: number) => number, X: number[]) { |
| 29 | + return (V: number[]): [number, number][] => X.map((x) => [x, mean(V, (v) => kernel(x - v))]); |
| 30 | + } |
| 31 | + |
| 32 | + function kernelEpanechnikov(k: number) { |
| 33 | + return (v: number) => { |
| 34 | + v /= k; |
| 35 | + return Math.abs(v) <= 1 ? (0.75 * (1 - v * v)) / k : 0; |
| 36 | + }; |
| 37 | + } |
| 38 | + |
| 39 | + const chartSize = getElementFontSize(container); |
| 40 | + |
| 41 | + const height = chartSize; |
| 42 | + const width = chartSize * 2; |
| 43 | + const padding = 1.5; |
| 44 | + |
| 45 | + // Clear old SVG |
| 46 | + container.innerHTML = ''; |
| 47 | + |
| 48 | + const valueExtent = extent(data); |
| 49 | + |
| 50 | + if (valueExtent[0] === undefined) { |
| 51 | + throw new Error('Input data is empty or invalid, cannot calculate value extent.'); |
| 52 | + } |
| 53 | + |
| 54 | + const xScale = scaleLinear(valueExtent, [padding, width - padding]); |
| 55 | + |
| 56 | + const kde = kernelDensityEstimator(kernelEpanechnikov(KDE_BANDWIDTH), ticks(valueExtent, TICK_COUNT)); |
| 57 | + const density = kde(data); |
| 58 | + |
| 59 | + const maxDensity = max(density, (d) => d[1]); |
| 60 | + const finalYScale = scaleLinear([0, maxDensity], [height - padding, padding]); |
| 61 | + |
| 62 | + const svgD3 = createSvg(container, width, height); |
| 63 | + |
| 64 | + const pathData = createCurvePath(xScale, finalYScale, density); |
| 65 | + |
| 66 | + svgD3 |
| 67 | + .append('path') |
| 68 | + .attr('class', 'mypath') |
| 69 | + .attr('fill', 'none') |
| 70 | + .attr('stroke', LINE_STROKE_COLOR) |
| 71 | + .attr('stroke-width', 1) |
| 72 | + .attr('stroke-linejoin', 'round') |
| 73 | + .attr('d', pathData); |
| 74 | +}; |
0 commit comments