Beeswarm
Two dot swarms, before and after, settle on an axis showing 3.4 versus 10.6.
Source
components/kuchi/beeswarm.tsx
1"use client";23import { loadFont } from "@remotion/google-fonts/DMSans";4import type React from "react";5import { useId, useMemo } from "react";6import {7 AbsoluteFill,8 Easing,9 interpolate,10 interpolateColors,11 spring,12 useCurrentFrame,13 useVideoConfig,14} from "remotion";1516const { fontFamily: sans } = loadFont("normal", {17 weights: ["400", "500"],18 subsets: ["latin"],19});2021export interface BeeswarmGroup {22 label: string;23 median: number;24 spread: number;25}2627export interface BeeswarmProps {28 before?: BeeswarmGroup;29 after?: BeeswarmGroup;30 count?: number;31 domain?: [number, number];32 tickStep?: number;33 axisLabel?: string;34 totalLabel?: string;35 accent?: string;36 /** Frames each dot takes to cross from the mixed swarm to its group. */37 split?: number;38 /** Weight of the two median numbers. */39 fontWeight?: number;40 /** Text color of the medians; overrides the theme ink. */41 ink?: string;42 /** Background fill; "transparent" drops it. */43 background?: string;44 /** Typeface for the copy. Load it yourself; DM Sans by default. */45 fontFamily?: string;46 /** Size of the chart, around the frame's center. */47 scale?: number;48 /** Frames to hold the first frame before anything moves. */49 delay?: number;50 /** Film grain over the scene. */51 grain?: boolean;52 speed?: number;53 theme?: "dark" | "light";54}5556const DEFAULT_BEFORE: BeeswarmGroup = {57 label: "Before",58 median: 3.4,59 spread: 0.85,60};61const DEFAULT_AFTER: BeeswarmGroup = {62 label: "With acme",63 median: 10.6,64 spread: 1.05,65};6667const EASE_IO = Easing.bezier(0.65, 0, 0.35, 1);68const EASE_OUT = Easing.bezier(0.22, 1, 0.36, 1);69const FALL = Easing.bezier(0.55, 0, 0.9, 0.6);70const CLAMP = {71 extrapolateLeft: "clamp",72 extrapolateRight: "clamp",73} as const;7475const THEMES = {76 dark: {77 bg: "#0A0A0B",78 fg: "#F3F2EF",79 muted: "#8B8A90",80 neutral: "#B9B8BD",81 grey: "#6E6D73",82 axis: "rgba(255,255,255,0.2)",83 rule: "rgba(255,255,255,0.07)",84 // gradients.sh "mesh" as a radial bloom through the hero cluster85 mesh: ["#ecdcf2", "#8796ee", "accent", "#2e45b7"],86 label: "#aab4f4",87 grain: 0.06,88 },89 light: {90 bg: "#F5F4F0",91 fg: "#121214",92 muted: "#6E6C67",93 neutral: "#5B5955",94 grey: "#A5A39D",95 axis: "rgba(18,18,20,0.22)",96 rule: "rgba(18,18,20,0.07)",97 mesh: ["#8796ee", "accent", "#2e45b7"],98 label: "#2e45b7",99 grain: 0.045,100 },101} as const;102103const POUR = [0, 40] as const;104const FALL_T = 16;105const SPLIT = 64;106const SPLIT_STAGGER = 10;107const SPLIT_T = 32;108109function hash(n: number) {110 const x = Math.sin(n * 127.1 + 311.7) * 43758.5453;111 return x - Math.floor(x);112}113114function normal(seed: number) {115 const a = Math.max(1e-6, hash(seed));116 const b = hash(seed + 91.7);117 return Math.sqrt(-2 * Math.log(a)) * Math.cos(2 * Math.PI * b);118}119120function swarm(xs: number[], d: number) {121 const order = xs.map((_, i) => i).sort((a, b) => xs[a] - xs[b]);122 const placed: { x: number; y: number }[] = [];123 const ys = new Array<number>(xs.length).fill(0);124 const d2 = d * d - 1e-6;125 for (const i of order) {126 const x = xs[i];127 const near = placed.filter((q) => Math.abs(q.x - x) < d);128 const cands = [0];129 for (const q of near) {130 const dy = Math.sqrt(Math.max(0, d * d - (q.x - x) ** 2));131 cands.push(q.y + dy, q.y - dy);132 }133 const flip = i % 2 === 0 ? 1 : -1;134 cands.sort((a, b) => Math.abs(a) - Math.abs(b) || (a - b) * flip);135 let y = 0;136 for (const c of cands) {137 if (near.every((q) => (q.x - x) ** 2 + (q.y - c) ** 2 >= d2)) {138 y = c;139 break;140 }141 }142 placed.push({ x, y });143 ys[i] = y;144 }145 return ys;146}147148/** The foreground at `scale`, around the frame's center; nothing extra at 1. */149function ScaleLayer({150 scale,151 children,152}: {153 scale: number;154 children: React.ReactNode;155}) {156 if (scale === 1) return children;157 return (158 <AbsoluteFill style={{ transform: `scale(${scale})` }}>159 {children}160 </AbsoluteFill>161 );162}163164function Grain({ opacity }: { opacity: number }) {165 const id = `g${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;166 return (167 <svg168 width="100%"169 height="100%"170 style={{ position: "absolute", inset: 0, opacity, pointerEvents: "none" }}171 aria-hidden172 >173 <filter id={id}>174 <feTurbulence175 type="fractalNoise"176 baseFrequency="0.9"177 numOctaves={2}178 seed={31}179 stitchTiles="stitch"180 />181 <feColorMatrix values="0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0.9 0" />182 </filter>183 <rect width="100%" height="100%" filter={`url(#${id})`} />184 </svg>185 );186}187188const fmt = (n: number) => n.toFixed(1).replace(/\.0$/, "");189190export function Beeswarm({191 before = DEFAULT_BEFORE,192 after = DEFAULT_AFTER,193 count = 200,194 domain = [0, 14],195 tickStep = 2,196 axisLabel = "launch videos shipped per quarter",197 totalLabel = "200 teams",198 accent = "#3B5BFD",199 split = SPLIT_T,200 fontWeight = 400,201 ink,202 background,203 fontFamily = sans,204 scale = 1,205 delay = 0,206 grain = true,207 speed = 1,208 theme = "dark",209}: BeeswarmProps) {210 const t = Math.max(0, useCurrentFrame() - delay) * speed;211 const { width: W, height: H, fps } = useVideoConfig();212 const u = Math.min(W / 1280, H / 720);213 const p = THEMES[theme];214 const fg = ink ?? p.fg;215 const stage = background ?? p.bg;216 const HIT = SPLIT + SPLIT_STAGGER + split - 4;217218 const N = Math.max(20, Math.min(320, Math.round(count)));219 const [d0, d1] = domain;220 const x0 = W * 0.12;221 const x1 = W * 0.88;222 const xOf = (v: number) => x0 + ((v - d0) / (d1 - d0 || 1)) * (x1 - x0);223 const axisY = H * 0.46;224 const r = 6.6 * u;225 const pitch = 2 * r + 1.2 * u;226227 const layout = useMemo(() => {228 const mid = (before.median + after.median) / 2;229 const midSpread = Math.max(before.spread, after.spread) * 1.45;230 const clampV = (v: number) => Math.min(d1 - 0.3, Math.max(d0 + 0.3, v));231 const v1 = Array.from({ length: N }, (_, i) =>232 clampV(mid + midSpread * normal(i * 2.31 + 0.17)),233 );234 const rank = v1235 .map((v, i) => ({ v, i }))236 .sort((a, b) => a.v - b.v)237 .map((o, k) => ({ i: o.i, score: k / N + (hash(o.i + 6.6) - 0.5) * 0.7 }))238 .sort((a, b) => a.score - b.score);239 const half = Math.floor(N / 2);240 const group = new Array<number>(N).fill(0);241 rank.forEach((o, k) => {242 group[o.i] = k < half ? 0 : 1;243 });244 const members = [0, 1].map((g) =>245 v1246 .map((v, i) => ({ v, i }))247 .filter((o) => group[o.i] === g)248 .sort((a, b) => a.v - b.v),249 );250 const v2 = new Array<number>(N).fill(0);251 members.forEach((list, g) => {252 const src = g === 0 ? before : after;253 const vals = list254 .map((_, k) =>255 clampV(src.median + src.spread * normal(k * 3.7 + g * 101.3)),256 )257 .sort((a, b) => a - b);258 const med = vals[Math.floor(vals.length / 2)] ?? src.median;259 list.forEach((o, k) => {260 v2[o.i] = vals[k] - med + src.median;261 });262 });263 const toX = (v: number) => x0 + ((v - d0) / (d1 - d0 || 1)) * (x1 - x0);264 const xs1 = v1.map(toX);265 const ys1 = swarm(xs1, pitch);266 const xs2 = v2.map(toX);267 const ys2 = [0, 1].reduce((acc, g) => {268 const idx = members[g].map((o) => o.i);269 const ys = swarm(270 idx.map((i) => xs2[i]),271 pitch,272 );273 idx.forEach((i, k) => {274 acc[i] = ys[k];275 });276 return acc;277 }, new Array<number>(N).fill(0));278 const pourOrder = ys1279 .map((y, i) => ({ i, k: y + (hash(i + 4.2) - 0.5) * pitch * 0.6 }))280 .sort((a, b) => b.k - a.k);281 const pourRank = new Array<number>(N).fill(0);282 pourOrder.forEach((o, k) => {283 pourRank[o.i] = k / Math.max(1, N - 1);284 });285 const ext = (g: number) =>286 Math.max(pitch, ...members[g].map((o) => Math.abs(ys2[o.i])));287 return {288 xs1,289 ys1,290 xs2,291 ys2,292 group,293 pourRank,294 ext1: Math.max(pitch, ...ys1.map(Math.abs)),295 ext: [ext(0), ext(1)],296 };297 }, [N, before, after, d0, d1, x0, x1, pitch]);298299 const ruleIn = interpolate(t, [0, 18], [0, 1], { ...CLAMP, easing: EASE_IO });300 const totalIn =301 interpolate(t, [POUR[1] + 6, POUR[1] + 16], [0, 1], {302 ...CLAMP,303 easing: EASE_OUT,304 }) * interpolate(t, [SPLIT - 2, SPLIT + 8], [1, 0], CLAMP);305 const push = interpolate(t, [0, HIT + 40], [0, 1], {306 ...CLAMP,307 easing: EASE_IO,308 });309 const camScale = 0.975 + 0.025 * push;310311 const meshId = `${useId().replace(/[^a-zA-Z0-9_-]/g, "")}-mesh`;312 const meshStops = p.mesh.map((c) => (c === "accent" ? accent : c));313 const bloomX = xOf(after.median);314 const bloomR = Math.max(315 after.spread * 2.4 * ((x1 - x0) / (d1 - d0 || 1)),316 layout.ext[1] * 1.6,317 );318 const circles: React.ReactNode[] = [];319 for (let i = 0; i < N; i++) {320 const g = layout.group[i];321 const start = POUR[0] + layout.pourRank[i] * (POUR[1] - POUR[0]);322 const fall = interpolate(t, [start, start + FALL_T], [0, 1], {323 ...CLAMP,324 easing: FALL,325 });326 if (fall <= 0) continue;327 const fromY = -H * 0.08 - hash(i + 12.1) * H * 0.12;328 const ty1 = axisY + layout.ys1[i];329 const landT = t - start - FALL_T;330 const settle =331 landT > 0 && landT < 8332 ? Math.sin((landT / 8) * Math.PI) * 1.6 * u * (1 - landT / 8)333 : 0;334 const y1 = fromY + (ty1 - fromY) * fall + settle;335 const sStart = SPLIT + hash(i + 2.9) * SPLIT_STAGGER;336 const k = interpolate(t, [sStart, sStart + split], [0, 1], {337 ...CLAMP,338 easing: EASE_IO,339 });340 const x = layout.xs1[i] + (layout.xs2[i] - layout.xs1[i]) * k;341 const y2 = axisY + layout.ys2[i];342 const lift = Math.sin(k * Math.PI) * (g === 0 ? -1 : 1) * 10 * u;343 const y = y1 + (y2 - y1) * k + lift;344 const o = interpolate(fall, [0, 0.25], [0, 1], CLAMP);345 if (g === 0) {346 const fill = interpolateColors(k, [0, 1], [p.neutral, p.grey]);347 circles.push(348 <circle key={i} cx={x} cy={y} r={r} fill={fill} opacity={o} />,349 );350 } else {351 circles.push(352 <g key={i} opacity={o}>353 {k < 1 && <circle cx={x} cy={y} r={r} fill={p.neutral} />}354 {k > 0 && (355 <circle cx={x} cy={y} r={r} fill={`url(#${meshId})`} opacity={k} />356 )}357 </g>,358 );359 }360 }361362 const ticks: number[] = [];363 for (let v = d0; v <= d1 + 1e-6; v += tickStep) ticks.push(v);364 const axisBase = axisY + Math.max(layout.ext1, ...layout.ext) + 72 * u;365366 const groups = [before, after].map((grp, g) => {367 const snap = spring({368 frame: t - HIT - g * 4,369 fps,370 config: { damping: 14, stiffness: 190, mass: 0.6 },371 });372 const a = interpolate(t, [HIT + g * 4, HIT + g * 4 + 8], [0, 1], CLAMP);373 const lab = interpolate(t, [HIT + 6 + g * 4, HIT + 24 + g * 4], [0, 1], {374 ...CLAMP,375 easing: EASE_OUT,376 });377 const ext = Math.max(...layout.ext) + 16 * u;378 return {379 grp,380 g,381 x: xOf(grp.median),382 top: axisY - ext,383 bot: axisY + ext,384 labelBottom: H - axisY + ext + 14 * u,385 snap,386 a,387 lab,388 color: g === 0 ? p.muted : p.label,389 line: g === 0 ? fg : accent,390 };391 });392393 return (394 <AbsoluteFill style={{ background: stage, overflow: "hidden" }}>395 <ScaleLayer scale={scale}>396 <AbsoluteFill397 style={{398 transform: `scale(${camScale})`,399 transformOrigin: "50% 50%",400 }}401 >402 <svg403 width={W}404 height={H}405 style={{ position: "absolute", inset: 0 }}406 aria-hidden407 >408 <line409 x1={W / 2 - ((x1 - x0) / 2) * ruleIn}410 x2={W / 2 + ((x1 - x0) / 2) * ruleIn}411 y1={axisY}412 y2={axisY}413 stroke={p.rule}414 strokeWidth={Math.max(1, u)}415 />416 <line417 x1={W / 2 - ((x1 - x0) / 2) * ruleIn}418 x2={W / 2 + ((x1 - x0) / 2) * ruleIn}419 y1={axisBase}420 y2={axisBase}421 stroke={p.axis}422 strokeWidth={Math.max(1, u)}423 />424 {ticks.map((v) => (425 <line426 key={v}427 x1={xOf(v)}428 x2={xOf(v)}429 y1={axisBase}430 y2={axisBase + 6 * u}431 stroke={p.axis}432 strokeWidth={Math.max(1, u)}433 opacity={ruleIn}434 />435 ))}436 <defs>437 <radialGradient438 id={meshId}439 gradientUnits="userSpaceOnUse"440 cx={bloomX + (push - 0.5) * 6 * u}441 cy={axisY}442 r={bloomR}443 >444 {meshStops.map((c, k) => (445 <stop446 key={c}447 offset={(k / (meshStops.length - 1)) ** 1.15}448 stopColor={c}449 />450 ))}451 </radialGradient>452 </defs>453 {circles}454 {groups.map((m) => {455 const len = (m.bot - m.top) * (0.4 + 0.6 * m.snap);456 const cy = (m.top + m.bot) / 2;457 return (458 <g key={m.grp.label} opacity={m.a}>459 <line460 x1={m.x}461 x2={m.x}462 y1={cy - len / 2}463 y2={cy + len / 2}464 stroke={stage === "transparent" ? p.bg : stage}465 strokeWidth={6 * u}466 strokeLinecap="round"467 />468 <line469 x1={m.x}470 x2={m.x}471 y1={cy - len / 2}472 y2={cy + len / 2}473 stroke={m.line}474 strokeWidth={2.4 * u}475 strokeLinecap="round"476 />477 </g>478 );479 })}480 </svg>481482 <div483 style={{484 position: "absolute",485 left: 0,486 width: W,487 top: axisY - layout.ext1 - 52 * u,488 textAlign: "center",489 fontFamily,490 fontWeight: 500,491 fontSize: 18 * u,492 letterSpacing: "-0.01em",493 color: p.muted,494 opacity: totalIn,495 }}496 >497 {totalLabel}498 </div>499500 {groups.map((m) => (501 <div502 key={`lab${m.grp.label}`}503 style={{504 position: "absolute",505 left: m.x - 200 * u,506 width: 400 * u,507 bottom: m.labelBottom,508 textAlign: "center",509 opacity: m.lab,510 transform: `translateY(${(1 - m.lab) * 10 * u}px)`,511 }}512 >513 <div514 style={{515 fontFamily,516 fontWeight: 500,517 fontSize: 18 * u,518 letterSpacing: "-0.01em",519 color: m.color,520 whiteSpace: "nowrap",521 }}522 >523 {m.grp.label}524 </div>525 <div526 style={{527 marginTop: 2 * u,528 fontFamily,529 fontWeight,530 fontSize: 64 * u,531 lineHeight: 1,532 letterSpacing: "-0.035em",533 color: fg,534 fontVariantNumeric: "tabular-nums",535 whiteSpace: "nowrap",536 }}537 >538 {fmt(m.grp.median)}539 </div>540 </div>541 ))}542543 {ticks.map((v) => (544 <div545 key={`t${v}`}546 style={{547 position: "absolute",548 left: xOf(v) - 30 * u,549 width: 60 * u,550 top: axisBase + 12 * u,551 textAlign: "center",552 fontFamily,553 fontWeight: 500,554 fontSize: 15 * u,555 color: p.muted,556 fontVariantNumeric: "tabular-nums",557 opacity: ruleIn,558 }}559 >560 {fmt(v)}561 </div>562 ))}563 <div564 style={{565 position: "absolute",566 left: 0,567 width: W,568 top: axisBase + 40 * u,569 textAlign: "center",570 fontFamily,571 fontWeight: 500,572 fontSize: 16 * u,573 color: p.muted,574 opacity: ruleIn,575 }}576 >577 {axisLabel}578 </div>579 </AbsoluteFill>580 </ScaleLayer>581 {grain ? <Grain opacity={p.grain} /> : null}582 </AbsoluteFill>583 );584}









