{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "scatter-plot",
  "title": "Scatter Plot",
  "description": "A scatter plot for spotting relationships: coloured groups of points that pop in on scroll, a least-squares trend line with its slope and R², legend toggles, and a nearest-point tooltip with guide lines and value pills on both axes.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/scatter-plot/scatter-plot.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type ChartTheme = \"dark\" | \"light\";\n\nexport interface ScatterGroup {\n  label: string;\n  /** Defaults to the theme palette. */\n  color?: string;\n}\n\nexport interface ScatterPoint {\n  x: number;\n  y: number;\n  /** Index into `groups`. */\n  group: number;\n  /** Optional name shown in the tooltip. */\n  label?: string;\n}\n\nexport interface ScatterPlotProps extends Omit<\n  React.ComponentPropsWithoutRef<\"div\">,\n  \"title\"\n> {\n  theme?: ChartTheme;\n  title?: string;\n  subtitle?: string;\n  groups?: ScatterGroup[];\n  points?: ScatterPoint[];\n  xLabel?: string;\n  yLabel?: string;\n  /** Draw a least-squares trend line through the visible points. */\n  showTrend?: boolean;\n  /** Height of the plot area, in px. */\n  height?: number;\n  formatX?: (value: number) => string;\n  formatY?: (value: number) => string;\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#0E0E0E\",\n    border: \"rgba(255,255,255,0.08)\",\n    text: \"#F4F5F7\",\n    sub: \"rgba(255,255,255,0.55)\",\n    grid: \"rgba(255,255,255,0.07)\",\n    axis: \"rgba(255,255,255,0.45)\",\n    tip: \"rgba(20,20,20,0.96)\",\n    tipBorder: \"rgba(255,255,255,0.12)\",\n    pill: \"#F4F5F7\",\n    pillText: \"#0E0E0E\",\n    trend: \"rgba(255,255,255,0.55)\",\n    series: [\"#87FFE3\", \"#8FB8FF\", \"#FF7A6B\", \"#F2A841\", \"#B69CFF\"],\n  },\n  light: {\n    card: \"#FFFFFF\",\n    border: \"rgba(0,0,0,0.07)\",\n    text: \"#111317\",\n    sub: \"rgba(17,19,23,0.55)\",\n    grid: \"rgba(17,19,23,0.08)\",\n    axis: \"rgba(17,19,23,0.5)\",\n    tip: \"rgba(255,255,255,0.98)\",\n    tipBorder: \"rgba(0,0,0,0.08)\",\n    pill: \"#111317\",\n    pillText: \"#FFFFFF\",\n    trend: \"rgba(17,19,23,0.5)\",\n    series: [\"#0E9F80\", \"#3B6FD8\", \"#E5484D\", \"#D9822B\", \"#7B5CE0\"],\n  },\n};\n\n// Deterministic sample data (same on server and client): ad spend vs signups for three segments.\nfunction samplePoints(): ScatterPoint[] {\n  let seed = 7;\n  const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;\n  const gauss = () => (rnd() + rnd() + rnd() - 1.5) / 1.5;\n  const out: ScatterPoint[] = [];\n  const shapes = [\n    { n: 22, x: [2, 18], slope: 38, base: 30, noise: 150 },\n    { n: 20, x: [9, 36], slope: 24, base: 260, noise: 260 },\n    { n: 16, x: [22, 58], slope: 17, base: 520, noise: 340 },\n  ];\n  shapes.forEach((s, g) => {\n    for (let i = 0; i < s.n; i++) {\n      const x = s.x[0] + rnd() * (s.x[1] - s.x[0]);\n      out.push({\n        x: Math.round(x * 10) / 10,\n        y: Math.max(10, Math.round(s.base + s.slope * x + gauss() * s.noise)),\n        group: g,\n        label: `Campaign ${String.fromCharCode(65 + g)}-${String(i + 1).padStart(2, \"0\")}`,\n      });\n    }\n  });\n  return out;\n}\n\nconst DEFAULT_GROUPS: ScatterGroup[] = [\n  { label: \"Startup\" },\n  { label: \"Mid-market\" },\n  { label: \"Enterprise\" },\n];\nconst DEFAULT_POINTS = samplePoints();\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(entry.contentRect.width),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\n/** 0 → 1 (linear) once the element scrolls into view; 1 straight away with reduced motion. */\nfunction useReveal(\n  ref: React.RefObject<HTMLElement | null>,\n  reduce: boolean,\n  duration = 1500,\n) {\n  const [t, setT] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el || reduce) return;\n    let raf = 0;\n    const io = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry.isIntersecting) return;\n        io.disconnect();\n        const start = performance.now();\n        const tick = (now: number) => {\n          const k = Math.min(1, (now - start) / duration);\n          setT(k);\n          if (k < 1) raf = requestAnimationFrame(tick);\n        };\n        raf = requestAnimationFrame(tick);\n      },\n      { threshold: 0.2 },\n    );\n    io.observe(el);\n    return () => {\n      io.disconnect();\n      cancelAnimationFrame(raf);\n    };\n  }, [ref, reduce, duration]);\n  return reduce ? 1 : t;\n}\n\nfunction niceScale(min: number, max: number, count = 5) {\n  const span = Math.max(1e-9, max - min);\n  const raw = span / count;\n  const mag = Math.pow(10, Math.floor(Math.log10(raw)));\n  const step =\n    [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? 10 * mag;\n  const lo = Math.floor(min / step) * step;\n  const hi = Math.ceil(max / step) * step;\n  return {\n    min: lo,\n    max: hi,\n    step,\n    ticks: Array.from(\n      { length: Math.round((hi - lo) / step) + 1 },\n      (_, i) => lo + i * step,\n    ),\n  };\n}\n\nconst clamp01 = (t: number) => Math.min(1, Math.max(0, t));\nconst easeOutBack = (t: number) =>\n  1 + 2.2 * Math.pow(t - 1, 3) + 1.2 * Math.pow(t - 1, 2);\n\nconst M = { top: 14, right: 16, bottom: 44, left: 56 };\n\nexport function ScatterPlot({\n  theme = \"dark\",\n  title = \"Ad spend vs signups\",\n  subtitle = \"Each dot is one campaign, last two quarters\",\n  groups = DEFAULT_GROUPS,\n  points = DEFAULT_POINTS,\n  xLabel = \"Ad spend ($K)\",\n  yLabel = \"Signups\",\n  showTrend = true,\n  height = 320,\n  formatX = (v) =>\n    `$${v.toLocaleString(\"en-US\", { maximumFractionDigits: 1 })}K`,\n  formatY = (v) => v.toLocaleString(\"en-US\", { maximumFractionDigits: 0 }),\n  className,\n  style,\n  ...props\n}: ScatterPlotProps) {\n  const pal = PALETTES[theme];\n  const reduce = useReducedMotion();\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(plotRef);\n  const reveal = useReveal(plotRef, reduce);\n  const [hidden, setHidden] = React.useState<boolean[]>(() =>\n    groups.map(() => false),\n  );\n  const [active, setActive] = React.useState<number | null>(null);\n  const [hoverGroup, setHoverGroup] = React.useState<number | null>(null);\n  const colors = groups.map(\n    (g, i) => g.color ?? pal.series[i % pal.series.length],\n  );\n\n  const plotW = Math.max(0, width - M.left - M.right);\n  const xs = niceScale(\n    Math.min(0, ...points.map((p) => p.x)),\n    Math.max(1, ...points.map((p) => p.x)),\n    Math.max(3, Math.min(6, Math.floor(plotW / 90))),\n  );\n  const ys = niceScale(\n    Math.min(0, ...points.map((p) => p.y)),\n    Math.max(1, ...points.map((p) => p.y)),\n    5,\n  );\n  const xAt = (v: number) =>\n    M.left + ((v - xs.min) / (xs.max - xs.min)) * plotW;\n  const yAt = (v: number) =>\n    M.top + height - ((v - ys.min) / (ys.max - ys.min)) * height;\n\n  // Points in x order: the order they pop in and the order arrow keys walk through.\n  const order = React.useMemo(\n    () => points.map((p, i) => ({ p, i })).sort((a, b) => a.p.x - b.p.x),\n    [points],\n  );\n  const visible = order.filter(({ p }) => !hidden[p.group]);\n\n  const trend = React.useMemo(() => {\n    const vis = points.filter((p) => !hidden[p.group]);\n    if (vis.length < 2) return null;\n    const mx = vis.reduce((s, p) => s + p.x, 0) / vis.length;\n    const my = vis.reduce((s, p) => s + p.y, 0) / vis.length;\n    let sxy = 0;\n    let sxx = 0;\n    let syy = 0;\n    for (const p of vis) {\n      sxy += (p.x - mx) * (p.y - my);\n      sxx += (p.x - mx) ** 2;\n      syy += (p.y - my) ** 2;\n    }\n    if (!sxx) return null;\n    const slope = sxy / sxx;\n    const r2 = syy ? (sxy * sxy) / (sxx * syy) : 0;\n    const x0 = Math.min(...vis.map((p) => p.x));\n    const x1 = Math.max(...vis.map((p) => p.x));\n    return {\n      slope,\n      r2,\n      x0,\n      x1,\n      y0: my + slope * (x0 - mx),\n      y1: my + slope * (x1 - mx),\n    };\n  }, [points, hidden]);\n\n  const nearest = (clientX: number, clientY: number) => {\n    const r = plotRef.current?.getBoundingClientRect();\n    if (!r) return;\n    const px = clientX - r.left;\n    const py = clientY - r.top;\n    let best: number | null = null;\n    let bestD = 28 * 28;\n    for (const { p, i } of visible) {\n      const d = (xAt(p.x) - px) ** 2 + (yAt(p.y) - py) ** 2;\n      if (d < bestD) {\n        bestD = d;\n        best = i;\n      }\n    }\n    setActive(best);\n  };\n  const onKey = (event: React.KeyboardEvent) => {\n    if (!visible.length) return;\n    const at = visible.findIndex(({ i }) => i === active);\n    let next = at;\n    if (event.key === \"ArrowRight\" || event.key === \"ArrowUp\")\n      next = at < 0 ? 0 : Math.min(visible.length - 1, at + 1);\n    else if (event.key === \"ArrowLeft\" || event.key === \"ArrowDown\")\n      next = at < 0 ? visible.length - 1 : Math.max(0, at - 1);\n    else if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = visible.length - 1;\n    else if (event.key === \"Escape\") return setActive(null);\n    else return;\n    event.preventDefault();\n    setActive(visible[next].i);\n  };\n\n  const ap = active !== null ? points[active] : null;\n  const tipX = ap ? xAt(ap.x) : 0;\n  const tipY = ap ? yAt(ap.y) : 0;\n  const tipFlip = tipX > width - 210;\n  const lineT = clamp01((reveal - 0.55) / 0.45);\n  const summary = `${title}. ${points.length} points in ${groups.length} groups. ${trend ? `Trend: each extra ${formatX(1)} adds about ${formatY(trend.slope)} ${yLabel.toLowerCase()}, R² ${trend.r2.toFixed(2)}.` : \"\"}`;\n\n  return (\n    <div\n      className={cn(\n        \"w-full overflow-hidden rounded-[20px] p-5 sm:p-7\",\n        className,\n      )}\n      style={{\n        background: pal.card,\n        border: `1px solid ${pal.border}`,\n        color: pal.text,\n        fontFamily: \"Inter, -apple-system, BlinkMacSystemFont, sans-serif\",\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-4\">\n        <div className=\"min-w-0\">\n          <p className=\"text-[15px] font-semibold tracking-[-0.01em]\">\n            {title}\n          </p>\n          {subtitle && (\n            <p className=\"mt-1 text-[12.5px]\" style={{ color: pal.sub }}>\n              {subtitle}\n            </p>\n          )}\n        </div>\n        {showTrend && trend && (\n          <div className=\"text-right\">\n            <p className=\"text-[20px] leading-tight font-semibold tracking-[-0.02em] tabular-nums\">\n              +{formatY(trend.slope)}\n            </p>\n            <p\n              className=\"mt-0.5 text-[11.5px] tabular-nums\"\n              style={{ color: pal.sub }}\n            >\n              {yLabel.toLowerCase()} per {formatX(1)} · R² {trend.r2.toFixed(2)}\n            </p>\n          </div>\n        )}\n      </div>\n\n      <div className=\"mt-4 flex flex-wrap gap-x-4 gap-y-2\">\n        {groups.map((g, i) => (\n          <button\n            key={g.label}\n            type=\"button\"\n            aria-pressed={!hidden[i]}\n            onClick={() => {\n              setActive(null);\n              setHidden((h) =>\n                h.filter((x) => !x).length === 1 && !h[i]\n                  ? h\n                  : h.map((x, j) => (j === i ? !x : x)),\n              );\n            }}\n            onMouseEnter={() => setHoverGroup(i)}\n            onMouseLeave={() => setHoverGroup(null)}\n            onFocus={() => setHoverGroup(i)}\n            onBlur={() => setHoverGroup(null)}\n            className=\"flex cursor-pointer items-center gap-1.5 text-[12px] font-medium transition-opacity\"\n            style={{ opacity: hidden[i] ? 0.4 : 1 }}\n          >\n            <span\n              className=\"size-2.5 rounded-full\"\n              style={{\n                background: hidden[i] ? \"transparent\" : colors[i],\n                boxShadow: `inset 0 0 0 1.5px ${colors[i]}`,\n              }}\n            />\n            {g.label}\n            <span style={{ color: pal.sub }}>\n              {points.filter((p) => p.group === i).length}\n            </span>\n          </button>\n        ))}\n        {showTrend && (\n          <span\n            className=\"flex items-center gap-1.5 text-[12px]\"\n            style={{ color: pal.sub }}\n          >\n            <span\n              className=\"w-4 border-t border-dashed\"\n              style={{ borderColor: pal.trend }}\n            />\n            Trend\n          </span>\n        )}\n      </div>\n\n      <div\n        ref={plotRef}\n        role=\"img\"\n        aria-label={summary}\n        tabIndex={0}\n        onKeyDown={onKey}\n        onPointerMove={(e) => nearest(e.clientX, e.clientY)}\n        onPointerDown={(e) => nearest(e.clientX, e.clientY)}\n        onPointerLeave={(e) => e.pointerType === \"mouse\" && setActive(null)}\n        onBlur={() => setActive(null)}\n        className=\"relative mt-3 w-full rounded-lg outline-none focus-visible:ring-2\"\n        style={{ height: height + M.top + M.bottom }}\n      >\n        {width > 0 && (\n          <svg\n            width={width}\n            height={height + M.top + M.bottom}\n            className=\"block overflow-visible\"\n            aria-hidden=\"true\"\n          >\n            {ys.ticks.map((t) => (\n              <g key={`y${t}`}>\n                <line\n                  x1={M.left}\n                  x2={M.left + plotW}\n                  y1={yAt(t)}\n                  y2={yAt(t)}\n                  stroke={pal.grid}\n                  strokeDasharray={t === ys.min ? undefined : \"3 4\"}\n                />\n                <text\n                  x={M.left - 10}\n                  y={yAt(t) + 4}\n                  textAnchor=\"end\"\n                  fontSize={11}\n                  fill={pal.axis}\n                  className=\"tabular-nums\"\n                >\n                  {formatY(t)}\n                </text>\n              </g>\n            ))}\n            {xs.ticks.map((t) => (\n              <g key={`x${t}`}>\n                <line\n                  x1={xAt(t)}\n                  x2={xAt(t)}\n                  y1={M.top}\n                  y2={M.top + height}\n                  stroke={pal.grid}\n                  strokeDasharray={t === xs.min ? undefined : \"3 4\"}\n                />\n                <text\n                  x={xAt(t)}\n                  y={M.top + height + 18}\n                  textAnchor=\"middle\"\n                  fontSize={11}\n                  fill={pal.axis}\n                  className=\"tabular-nums\"\n                >\n                  {formatX(t)}\n                </text>\n              </g>\n            ))}\n            <text\n              x={M.left + plotW}\n              y={M.top + height + 38}\n              textAnchor=\"end\"\n              fontSize={11}\n              fontWeight={500}\n              fill={pal.sub}\n            >\n              {xLabel} →\n            </text>\n            <text\n              x={M.left + 8}\n              y={M.top + 12}\n              fontSize={11}\n              fontWeight={500}\n              fill={pal.sub}\n            >\n              ↑ {yLabel}\n            </text>\n\n            {showTrend && trend && (\n              <line\n                x1={xAt(trend.x0)}\n                y1={yAt(trend.y0)}\n                x2={xAt(trend.x0 + (trend.x1 - trend.x0) * lineT)}\n                y2={yAt(trend.y0 + (trend.y1 - trend.y0) * lineT)}\n                stroke={pal.trend}\n                strokeWidth={1.5}\n                strokeDasharray=\"6 5\"\n              />\n            )}\n\n            {ap && (\n              <g\n                stroke={colors[ap.group]}\n                strokeOpacity={0.5}\n                strokeDasharray=\"2 3\"\n              >\n                <line x1={M.left} x2={tipX} y1={tipY} y2={tipY} />\n                <line x1={tipX} x2={tipX} y1={tipY} y2={M.top + height} />\n              </g>\n            )}\n\n            {order.map(({ p, i }, k) => {\n              const s = reduce\n                ? 1\n                : easeOutBack(clamp01(reveal * 1.8 - (k / order.length) * 0.8));\n              const off = hidden[p.group];\n              const dim =\n                (hoverGroup !== null && !hidden[hoverGroup] && hoverGroup !== p.group) ||\n                (active !== null && active !== i);\n              return (\n                <circle\n                  key={i}\n                  cx={xAt(p.x)}\n                  cy={yAt(p.y)}\n                  r={(active === i ? 7 : 5) * (off ? 0 : Math.max(0, s))}\n                  fill={colors[p.group]}\n                  fillOpacity={dim ? 0.25 : 0.85}\n                  stroke={active === i ? pal.card : \"none\"}\n                  strokeWidth={2}\n                  style={{ transition: \"r 220ms, fill-opacity 160ms\" }}\n                />\n              );\n            })}\n            {ap && (\n              <circle\n                cx={tipX}\n                cy={tipY}\n                r={11}\n                fill=\"none\"\n                stroke={colors[ap.group]}\n                strokeWidth={1.5}\n                strokeOpacity={0.6}\n              />\n            )}\n\n            {ap && (\n              <g fontSize={10.5} fontWeight={600} className=\"tabular-nums\">\n                <rect\n                  x={M.left - 52}\n                  y={tipY - 9}\n                  width={46}\n                  height={18}\n                  rx={5}\n                  fill={pal.pill}\n                />\n                <text\n                  x={M.left - 29}\n                  y={tipY + 4}\n                  textAnchor=\"middle\"\n                  fill={pal.pillText}\n                >\n                  {formatY(ap.y)}\n                </text>\n                <rect\n                  x={tipX - 30}\n                  y={M.top + height + 5}\n                  width={60}\n                  height={18}\n                  rx={5}\n                  fill={pal.pill}\n                />\n                <text\n                  x={tipX}\n                  y={M.top + height + 18}\n                  textAnchor=\"middle\"\n                  fill={pal.pillText}\n                >\n                  {formatX(ap.x)}\n                </text>\n              </g>\n            )}\n          </svg>\n        )}\n        {ap && width > 0 && (\n          <div\n            className=\"pointer-events-none absolute z-10 min-w-[160px] rounded-xl px-3 py-2.5 text-[12px] shadow-xl\"\n            style={{\n              left: tipFlip ? undefined : tipX + 16,\n              right: tipFlip ? width - tipX + 16 : undefined,\n              top: Math.max(0, tipY - 70),\n              background: pal.tip,\n              border: `1px solid ${pal.tipBorder}`,\n              backdropFilter: \"blur(8px)\",\n            }}\n          >\n            <p className=\"flex items-center gap-1.5 font-semibold\">\n              <span\n                className=\"size-2 rounded-full\"\n                style={{ background: colors[ap.group] }}\n              />\n              {ap.label ?? groups[ap.group]?.label}\n            </p>\n            <p className=\"mt-0.5\" style={{ color: pal.sub }}>\n              {groups[ap.group]?.label}\n            </p>\n            <div className=\"mt-2 flex justify-between gap-4\">\n              <span style={{ color: pal.sub }}>{xLabel}</span>\n              <span className=\"font-semibold tabular-nums\">\n                {formatX(ap.x)}\n              </span>\n            </div>\n            <div className=\"mt-1 flex justify-between gap-4\">\n              <span style={{ color: pal.sub }}>{yLabel}</span>\n              <span className=\"font-semibold tabular-nums\">\n                {formatY(ap.y)}\n              </span>\n            </div>\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}