Scatter Plot
ChartsX-Y scatter plot with data points.
Preview
Usage
example.jsx
import { ScatterPlot } from "@/components/ui/scatter-plot";
export default function Example() {
return <ScatterPlot />;
}Source Code
Copy this file into components/ui/scatter-plot.jsx in your project.
scatter-plot.jsx
"use client";
import { forwardRef } from "react";
import { cn } from "@/lib/utils";
const ScatterPlot = forwardRef(({ className, data = [], width = 400, height = 300, color = "var(--primary)", ...props }, ref) => {
const maxX = Math.max(...data.map((d) => d.x), 1);
const maxY = Math.max(...data.map((d) => d.y), 1);
const padX = 50, padY = 20;
const chartW = width - padX - 20;
const chartH = height - padY * 2 - 10;
return (
<div ref={ref} className={cn("inline-block", className)} {...props}>
<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
<line x1={padX} y1={padY} x2={padX} y2={height - padY - 10} stroke="currentColor" opacity="0.2" />
<line x1={padX} y1={height - padY - 10} x2={width - 20} y2={height - padY - 10} stroke="currentColor" opacity="0.2" />
{data.map((d, i) => (
<circle key={i} cx={padX + (d.x / maxX) * chartW} cy={padY + chartH - (d.y / maxY) * chartH}
r={d.size || 4} fill={d.color || color} opacity="0.7"
/>
))}
</svg>
</div>
);
});
ScatterPlot.displayName = "ScatterPlot";
export { ScatterPlot };
Quick Install
Make sure you have the cn() utility set up. It requires clsx and tailwind-merge.
npm install clsx tailwind-merge