{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "scatter-chart",
  "type": "registry:ui",
  "title": "Scatter chart",
  "description": "React scatter and bubble chart in plain SVG with rounded axis ticks, reference lines, hover that snaps to the nearest point and arrow-key point navigation.",
  "author": "MiniDev UI <https://ui.minidev.pro>",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.minidev.pro/r/chart-legend.json",
    "https://ui.minidev.pro/r/chart-tooltip-card.json",
    "utils"
  ],
  "files": [
    {
      "path": "registry/ui/scatter-chart.tsx",
      "type": "registry:ui",
      "target": "components/ui/scatter-chart.tsx",
      "content": "\"use client\"\nimport * as React from \"react\"\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\"\nimport { cn } from \"@/lib/utils\"\nimport { ChartLegend } from \"@/components/ui/chart-legend\"\nimport { ChartTooltipCard } from \"@/components/ui/chart-tooltip-card\"\n\n/**\n * ScatterChart — plots two numbers against each other in SVG; the pointer snaps to the nearest point and the arrow keys walk them.\n *\n * Use it to show how two measures relate across many items: deal size against win rate, price against\n * rating, latency against payload. Give points a `size` and it becomes a bubble chart. For one measure over\n * time use LineChart or InteractiveAreaChart; for totals by category use BarChart. No chart library: ticks are\n * rounded to 1, 2, 2.5 or 5 steps, and hovering a ChartLegend entry dims the other series.\n *\n * @example\n * <ScatterChart\n *   label=\"Deal size against days to close\"\n *   xLabel=\"Deal size\"\n *   yLabel=\"Days to close\"\n *   xFormat={{ style: \"currency\", currency: \"USD\", notation: \"compact\" }}\n *   series={[{ name: \"Inbound\", points: [{ x: 12000, y: 21 }, { x: 48000, y: 64, label: \"Northwind\" }] }]}\n * />\n */\n\nconst DATA = { type: \"spring\", bounce: 0.12, duration: 0.7 } as const\nconst SNAPPY = { type: \"spring\", bounce: 0.18, duration: 0.42 } as const\nconst INSTANT = { duration: 0 } as const\n\ntype ChartColor = \"chart-1\" | \"chart-2\" | \"chart-3\" | \"chart-4\" | \"chart-5\"\nconst COLORS: ChartColor[] = [\"chart-1\", \"chart-2\", \"chart-3\", \"chart-4\", \"chart-5\"]\n\ntype ScatterPoint = {\n  x: number\n  y: number\n  /** Bubble size, any positive number. When any point has one, the chart becomes a bubble chart. */\n  size?: number\n  /** Name of the point, shown as the tooltip title and read by screen readers. */\n  label?: string\n}\n\ntype ScatterSeries = {\n  /** Series name, used in the legend, tooltip and point labels. Keep it unique. */\n  name: string\n  /** Chart colour token. Defaults to chart-1 to chart-5 in series order. */\n  color?: ChartColor\n  points: ScatterPoint[]\n}\n\ntype ReferenceLine = {\n  /** \"y\" draws a horizontal line at a y value, \"x\" a vertical line at an x value. */\n  axis: \"x\" | \"y\"\n  value: number\n  /** Short text drawn at the end of the line, such as \"Target\" or \"Median\". */\n  label?: string\n}\n\ntype Format = Intl.NumberFormatOptions | ((n: number) => string)\n\n// Lumen accounts: annual contract value against days to close.\nconst SAMPLE: ScatterSeries[] = [\n  {\n    name: \"Inbound\",\n    points: [\n      { x: 8400, y: 14, label: \"Juniper Studio\" }, { x: 12600, y: 19 }, { x: 15800, y: 24 }, { x: 22400, y: 21 },\n      { x: 26800, y: 33 }, { x: 31200, y: 29 }, { x: 38600, y: 41 }, { x: 44200, y: 38 }, { x: 52800, y: 47, label: \"Helix Biotech\" },\n    ],\n  },\n  {\n    name: \"Outbound\",\n    points: [\n      { x: 18200, y: 46 }, { x: 24600, y: 52 }, { x: 33400, y: 61 }, { x: 41800, y: 58 }, { x: 56200, y: 74 },\n      { x: 63800, y: 69, label: \"Meridian Freight\" }, { x: 72400, y: 88 }, { x: 86600, y: 96, label: \"Cobalt Systems\" },\n    ],\n  },\n]\n\n/** Ticks on a 1, 2, 2.5 or 5 step that cover [lo, hi]; the first and last tick are the domain. */\nfunction niceTicks(lo: number, hi: number, count = 5): number[] {\n  if (!Number.isFinite(lo) || !Number.isFinite(hi)) return [0, 1]\n  if (lo === hi) {\n    const pad = Math.abs(lo) || 1\n    lo -= pad\n    hi += pad\n  }\n  const raw = (hi - lo) / count\n  const pow = 10 ** Math.floor(Math.log10(raw))\n  const f = raw / pow\n  const step = (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * pow\n  const ticks: number[] = []\n  for (let v = Math.floor(lo / step) * step; v <= Math.ceil(hi / step) * step + step / 2; v += step) {\n    ticks.push(Number(v.toPrecision(12)))\n  }\n  return ticks\n}\n\n// Bubbles paint largest first, so a small bubble is never hidden under a big one.\nconst drawOrder = (points: ScatterPoint[]) =>\n  points.map((_, i) => i).sort((a, b) => (points[b]!.size ?? 0) - (points[a]!.size ?? 0))\n\nfunction formatter(f: Format | undefined, locale: string) {\n  if (typeof f === \"function\") return f\n  const nf = new Intl.NumberFormat(locale, f ?? { maximumFractionDigits: 2 })\n  return (n: number) => nf.format(n)\n}\n\ntype ScatterChartProps = {\n  /** One or more series of `{ x, y, size?, label? }` points. */\n  series?: ScatterSeries[]\n  /** X axis title, also used in the tooltip and point labels. */\n  xLabel?: string\n  /** Y axis title, also used in the tooltip and point labels. */\n  yLabel?: string\n  /** Intl.NumberFormat options (works from Server Components) or a function, for x ticks and values. */\n  xFormat?: Format\n  /** Intl.NumberFormat options or a function, for y ticks and values. */\n  yFormat?: Format\n  /** What `size` measures, shown in the tooltip in bubble mode. */\n  sizeLabel?: string\n  /** Smallest and largest bubble diameter in px. Bubble area grows with `size`. */\n  sizeRange?: [number, number]\n  /** Dashed lines at fixed values, such as a target or a median. Included in the axis range. */\n  referenceLines?: ReferenceLine[]\n  /** Plot height in px, not counting the axis labels and legend. */\n  height?: number\n  /** Locale for number formatting. Fixed by default so server and browser render the same text. */\n  locale?: string\n  /** Show a ChartLegend under the chart when there is more than one series. */\n  legend?: boolean\n  /** Accessible name of the chart. */\n  label?: string\n  className?: string\n}\n\nfunction ScatterChart({\n  series = SAMPLE,\n  xLabel,\n  yLabel,\n  xFormat,\n  yFormat,\n  sizeLabel = \"Size\",\n  sizeRange = [8, 40],\n  referenceLines = [],\n  height = 280,\n  locale = \"en-US\",\n  legend = true,\n  label = \"Scatter chart\",\n  className,\n}: ScatterChartProps) {\n  const reduce = useReducedMotion()\n  const pointEls = React.useRef<(HTMLSpanElement | null)[]>([])\n  const [active, setActive] = React.useState<number | null>(null)\n  const [roving, setRoving] = React.useState(0)\n  const [dimmed, setDimmed] = React.useState<number | null>(null)\n\n  const fx = formatter(xFormat, locale)\n  const fy = formatter(yFormat, locale)\n  const fs = formatter(undefined, locale)\n\n  const all = series.flatMap((s) => s.points)\n  const refX = referenceLines.filter((r) => r.axis === \"x\").map((r) => r.value)\n  const refY = referenceLines.filter((r) => r.axis === \"y\").map((r) => r.value)\n  const xs = [...all.map((p) => p.x), ...refX]\n  const ys = [...all.map((p) => p.y), ...refY]\n  const xTicks = niceTicks(Math.min(...xs), Math.max(...xs))\n  const yTicks = niceTicks(Math.min(...ys), Math.max(...ys))\n  const x0 = xTicks[0]!\n  const x1 = xTicks.at(-1)!\n  const y0 = yTicks[0]!\n  const y1 = yTicks.at(-1)!\n  const px = (v: number) => (v - x0) / (x1 - x0 || 1)\n  const py = (v: number) => 1 - (v - y0) / (y1 - y0 || 1)\n\n  const sizes = all.flatMap((p) => (p.size != null && p.size > 0 ? [p.size] : []))\n  const bubble = sizes.length > 0\n  const maxSize = Math.max(...sizes, 1)\n  // Area, not radius, tracks size, so a bubble twice the value looks twice as big.\n  const diameter = (s?: number) => {\n    if (!bubble) return 8\n    const [lo, hi] = sizeRange\n    const t = Math.max(s ?? 0, 0) / maxSize\n    return Math.sqrt(lo * lo + t * (hi * hi - lo * lo))\n  }\n\n  // Every point in x order: the keyboard walks this list and the pointer searches it.\n  const order = series\n    .flatMap((s, si) => s.points.map((p, pi) => ({ si, pi, p, left: px(p.x), top: py(p.y) })))\n    .sort((a, b) => a.p.x - b.p.x || a.p.y - b.p.y)\n  const slot = new Map(order.map((o, k) => [`${o.si}:${o.pi}`, k]))\n  const tabStop = Math.min(roving, Math.max(order.length - 1, 0))\n\n  const colorOf = (si: number) => `var(--${series[si]?.color ?? COLORS[si % COLORS.length]})`\n  const describe = (o: (typeof order)[number]) => {\n    const s = series[o.si]!\n    const parts = [s.name, o.p.label, `${xLabel ?? \"x\"} ${fx(o.p.x)}`, `${yLabel ?? \"y\"} ${fy(o.p.y)}`]\n    if (bubble && o.p.size != null) parts.push(`${sizeLabel} ${fs(o.p.size)}`)\n    return parts.filter(Boolean).join(\", \")\n  }\n\n  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n    const r = e.currentTarget.getBoundingClientRect()\n    let best = -1\n    let bestD = Infinity\n    order.forEach((o, k) => {\n      if (dimmed != null && o.si !== dimmed) return\n      const d = (o.left * r.width - (e.clientX - r.left)) ** 2 + (o.top * r.height - (e.clientY - r.top)) ** 2\n      if (d < bestD) {\n        bestD = d\n        best = k\n      }\n    })\n    setActive(best < 0 ? null : best)\n  }\n\n  const onKeyDown = (e: React.KeyboardEvent, k: number) => {\n    const next =\n      e.key === \"ArrowRight\" || e.key === \"ArrowDown\" ? k + 1\n      : e.key === \"ArrowLeft\" || e.key === \"ArrowUp\" ? k - 1\n      : e.key === \"Home\" ? 0\n      : e.key === \"End\" ? order.length - 1\n      : null\n    if (next == null) return\n    e.preventDefault()\n    const to = Math.max(0, Math.min(order.length - 1, next))\n    pointEls.current[to]?.focus()\n  }\n\n  const cur = active != null ? order[active] : undefined\n  const widestY = yTicks.map(fy).reduce((a, b) => (b.length > a.length ? b : a), \"\")\n\n  return (\n    <div data-slot=\"scatter-chart\" className={cn(\"flex w-full flex-col gap-2\", className)}>\n      {yLabel ? <p className=\"text-xs text-fg-muted\">{yLabel}</p> : null}\n      <div className=\"grid grid-cols-[auto_minmax(0,1fr)] gap-x-2\">\n        <div aria-hidden className=\"relative font-mono text-[10px] text-fg-subtle tabular-nums\" style={{ height }}>\n          <span className=\"invisible block\">{widestY}</span>\n          {yTicks.map((t) => (\n            <span key={t} className=\"absolute right-0 -translate-y-1/2 whitespace-nowrap\" style={{ top: `${py(t) * 100}%` }}>\n              {fy(t)}\n            </span>\n          ))}\n        </div>\n        <div\n          role=\"group\"\n          aria-label={`${label}, ${series.length} series, ${order.length} points`}\n          className=\"relative cursor-crosshair touch-pan-y\"\n          style={{ height }}\n          onPointerMove={onPointerMove}\n          onPointerLeave={() => setActive(null)}\n          onBlur={(e) => {\n            if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setActive(null)\n          }}\n        >\n          <svg aria-hidden viewBox=\"0 0 100 100\" preserveAspectRatio=\"none\" className=\"absolute inset-0 size-full overflow-visible\">\n            {yTicks.map((t, i) => (\n              <line key={`y${t}`} x1=\"0\" x2=\"100\" y1={py(t) * 100} y2={py(t) * 100} className=\"stroke-border\" strokeWidth=\"1\" strokeDasharray={i === 0 ? undefined : \"2 3\"} vectorEffect=\"non-scaling-stroke\" />\n            ))}\n            {xTicks.map((t, i) => (\n              <line key={`x${t}`} x1={px(t) * 100} x2={px(t) * 100} y1=\"0\" y2=\"100\" className=\"stroke-border\" strokeWidth=\"1\" strokeDasharray={i === 0 ? undefined : \"2 3\"} vectorEffect=\"non-scaling-stroke\" />\n            ))}\n            {referenceLines.map((r, i) =>\n              r.axis === \"y\" ? (\n                <line key={i} x1=\"0\" x2=\"100\" y1={py(r.value) * 100} y2={py(r.value) * 100} className=\"stroke-fg-subtle\" strokeWidth=\"1.5\" strokeDasharray=\"5 4\" vectorEffect=\"non-scaling-stroke\" />\n              ) : (\n                <line key={i} x1={px(r.value) * 100} x2={px(r.value) * 100} y1=\"0\" y2=\"100\" className=\"stroke-fg-subtle\" strokeWidth=\"1.5\" strokeDasharray=\"5 4\" vectorEffect=\"non-scaling-stroke\" />\n              )\n            )}\n            {cur ? (\n              <g className=\"stroke-fg-subtle\" strokeWidth=\"1\" strokeDasharray=\"3 3\">\n                <line x1={cur.left * 100} x2={cur.left * 100} y1=\"0\" y2=\"100\" vectorEffect=\"non-scaling-stroke\" />\n                <line x1=\"0\" x2=\"100\" y1={cur.top * 100} y2={cur.top * 100} vectorEffect=\"non-scaling-stroke\" />\n              </g>\n            ) : null}\n          </svg>\n          {referenceLines.map((r, i) =>\n            r.label ? (\n              <span\n                key={i}\n                aria-hidden\n                className={cn(\n                  \"pointer-events-none absolute text-[10px] whitespace-nowrap text-fg-muted\",\n                  r.axis === \"y\" ? \"right-1 -translate-y-full pb-0.5\" : \"top-1 pl-1\"\n                )}\n                style={r.axis === \"y\" ? { top: `${py(r.value) * 100}%` } : { left: `${px(r.value) * 100}%` }}\n              >\n                {r.label}\n              </span>\n            ) : null\n          )}\n          {series.map((s, si) => (\n            <div\n              key={s.name}\n              className=\"pointer-events-none absolute inset-0 transition-opacity duration-[140ms] ease-hairline\"\n              style={{ opacity: dimmed != null && dimmed !== si ? 0.16 : 1 }}\n            >\n              <AnimatePresence initial={false}>\n                {drawOrder(s.points).map((pi) => {\n                  const p = s.points[pi]!\n                  const k = slot.get(`${si}:${pi}`) ?? 0\n                  const d = diameter(p.size)\n                  const color = colorOf(si)\n                  const pos = { left: `${px(p.x) * 100}%`, top: `${py(p.y) * 100}%` }\n                  return (\n                    <motion.span\n                      key={pi}\n                      ref={(el) => {\n                        pointEls.current[k] = el\n                      }}\n                      role=\"img\"\n                      aria-label={describe(order[k]!)}\n                      tabIndex={k === tabStop ? 0 : -1}\n                      onFocus={() => {\n                        setActive(k)\n                        setRoving(k)\n                      }}\n                      onKeyDown={(e) => onKeyDown(e, k)}\n                      initial={{ opacity: 0, scale: 0.4, ...pos }}\n                      animate={{ opacity: 1, scale: 1, ...pos }}\n                      exit={{ opacity: 0, scale: 0.4 }}\n                      transition={reduce ? INSTANT : { default: DATA, opacity: SNAPPY, scale: SNAPPY }}\n                      className={cn(\n                        \"absolute -translate-x-1/2 -translate-y-1/2 rounded-full outline-none\",\n                        \"focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-surface\",\n                        bubble ? \"border-[1.5px]\" : \"border-[1.5px] border-surface\"\n                      )}\n                      style={{\n                        width: d,\n                        height: d,\n                        background: bubble ? `color-mix(in oklab, ${color} 26%, transparent)` : color,\n                        borderColor: bubble ? color : undefined,\n                        zIndex: active === k ? 2 : undefined,\n                      }}\n                    />\n                  )\n                })}\n              </AnimatePresence>\n            </div>\n          ))}\n          {cur ? (\n            <span\n              aria-hidden\n              className=\"pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 rounded-full border-2\"\n              style={{\n                left: `${cur.left * 100}%`,\n                top: `${cur.top * 100}%`,\n                width: diameter(cur.p.size) + 8,\n                height: diameter(cur.p.size) + 8,\n                borderColor: colorOf(cur.si),\n              }}\n            />\n          ) : null}\n          {order.length === 0 ? (\n            <p className=\"absolute inset-0 grid place-items-center text-xs text-fg-muted\">No data</p>\n          ) : null}\n          {cur ? (\n            // aria-hidden: the focused point's own label already tells screen readers the same values.\n            <div\n              aria-hidden\n              className={cn(\n                \"pointer-events-none absolute z-10 -translate-y-1/2\",\n                cur.left > 0.6 ? \"-translate-x-full pr-4\" : \"pl-4\"\n              )}\n              style={{ left: `${cur.left * 100}%`, top: `${cur.top * 100}%` }}\n            >\n              <ChartTooltipCard\n                title={cur.p.label ? (series.length > 1 ? `${cur.p.label} · ${series[cur.si]!.name}` : cur.p.label) : series[cur.si]!.name}\n                rows={[\n                  { label: xLabel ?? \"x\", value: fx(cur.p.x) },\n                  { label: yLabel ?? \"y\", value: fy(cur.p.y) },\n                  ...(bubble && cur.p.size != null ? [{ label: sizeLabel, value: fs(cur.p.size) }] : []),\n                ]}\n              />\n            </div>\n          ) : null}\n        </div>\n        <div />\n        <div aria-hidden className=\"relative mt-1.5 h-4 font-mono text-[10px] text-fg-subtle tabular-nums\">\n          {xTicks.map((t, i) => (\n            <span\n              key={t}\n              // The end labels align inward so they never spill past the plot.\n              className={cn(\"absolute whitespace-nowrap\", i === 0 ? \"\" : i === xTicks.length - 1 ? \"-translate-x-full\" : \"-translate-x-1/2\")}\n              style={{ left: `${px(t) * 100}%` }}\n            >\n              {fx(t)}\n            </span>\n          ))}\n        </div>\n      </div>\n      {xLabel ? <p className=\"text-right text-xs text-fg-muted\">{xLabel}</p> : null}\n      {legend && series.length > 1 ? (\n        <div\n          onPointerOver={(e) => {\n            const li = (e.target as HTMLElement).closest(\"li\")\n            if (li?.parentElement) setDimmed(Array.prototype.indexOf.call(li.parentElement.children, li))\n          }}\n          onPointerLeave={() => setDimmed(null)}\n        >\n          <ChartLegend label={`${label} legend`} items={series.map((s, si) => ({ label: s.name, color: colorOf(si) }))} />\n        </div>\n      ) : null}\n    </div>\n  )\n}\n\nexport { ScatterChart }\nexport type { ScatterChartProps, ScatterSeries, ScatterPoint, ReferenceLine as ScatterReferenceLine }\n"
    }
  ],
  "categories": [
    "charts"
  ],
  "docs": "import { ScatterChart } from \"@/components/ui/scatter-chart\"\nNeeds the MiniDev tokens stylesheet (https://ui.minidev.pro/r/styles.css) imported after Tailwind.\nDocs: https://ui.minidev.pro/docs/scatter-chart · Markdown for agents: https://ui.minidev.pro/docs/scatter-chart.md",
  "meta": {
    "tier": "free",
    "kind": "ui",
    "category": "charts",
    "import": "@/components/ui/scatter-chart",
    "npmImport": "minidev-ui-kit/ui/scatter-chart",
    "exports": [
      "ScatterChart"
    ],
    "related": [
      "line-chart",
      "interactive-area-chart",
      "bar-chart",
      "chart-legend"
    ],
    "docsUrl": "https://ui.minidev.pro/docs/scatter-chart",
    "markdownUrl": "https://ui.minidev.pro/docs/scatter-chart.md",
    "keywords": [
      "shadcn scatter chart",
      "react scatter plot",
      "react bubble chart"
    ]
  }
}
