# Linear Regression

> Scatterplot with fitted linear regression trend line.

A shadcn/ui block from the [@paceui](https://paceui.com/?utm_source=shadcn.exchange) registry, listed on [shadcn.exchange](https://shadcn.exchange/r/paceui/tanstack-charts-linear-regression).

- Page, with a live preview: https://shadcn.exchange/r/paceui/tanstack-charts-linear-regression
- Screenshot: https://abzjhwgwpdpz7ua5.public.blob.vercel-storage.com/shots/paceui/tanstack-charts-linear-regression-light-5be442ce3ecc31c1.png
- Registry item: https://paceui.com/r/tanstack-charts-linear-regression.json
- Listed: 2026-10-21, source last changed 2026-10-21

## Install

```bash
npx shadcn@latest add https://shadcn.exchange/r/paceui/tanstack-charts-linear-regression.json
```

Run it in a project that has shadcn/ui set up. It adds the files below and installs what they depend on.

## Dependencies

- npm packages: `@tanstack/charts`, `@tanstack/react-charts`, `d3-scale`
- Registry items: `card`

## Files

### `components/tanstack-charts/line/linear-regression.tsx`

```tsx
import { type ChartPoint, defineChart, dot, linearRegressionY } from "@tanstack/charts";
import { motion } from "@tanstack/charts/motion";
import { tooltip } from "@tanstack/charts/tooltip";
import { Chart } from "@tanstack/react-charts/core";
import { useMemo } from "react";

import { scaleLinear } from "d3-scale";
import { TrendingDown } from "lucide-react";

import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";

interface CarDatum {
    name: string;
    hp: number;
    mpg: number;
}

const motionRenderer = motion({
    initial: "always",
    transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});

function generateDemoData(): CarDatum[] {
    const results: CarDatum[] = [];
    for (let i = 0; i < 40; i++) {
        const hp = 50 + i * 4 + Math.sin(i) * 10;
        const mpg = 45 - hp * 0.15 + Math.cos(i * 1.2) * 4;
        results.push({
            name: `Model-${i + 1}`,
            hp: Math.round(hp),
            mpg: Math.max(10, Number(mpg.toFixed(1))),
        });
    }
    return results;
}

function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
    if (points.length === 0) return { title: "", rows: [] };
    const p = points[0];
    const d = p.datum as any;
    if (!d) return { title: "", rows: [] };
    if ("name" in d) {
        return {
            title: d.name,
            rows: [
                { label: "Power", value: `${d.hp} hp`, color: "var(--chart-1)" },
                { label: "Fuel Economy", value: `${d.mpg} mpg`, color: "var(--foreground)" },
            ],
        };
    }
    return {
        title: "Regression Line Trend",
        rows: [{ label: "Predicted MPG", value: `${Number(d.y).toFixed(1)} mpg`, color: "var(--chart-2)" }],
    };
}

export function LinearRegressionChart() {
    const data = useMemo(() => generateDemoData(), []);

    const definition = useMemo(
        () =>
            defineChart(
                {
                    renderer: motionRenderer,
                    marks: [
                        dot(data, {
                            id: "car-dots",
                            x: "hp",
                            y: "mpg",
                            fill: "var(--chart-1)",
                            r: 3.5,
                        }),
                        linearRegressionY(data, {
                            id: "regression-line",
                            x: "hp",
                            y: "mpg",
                            ci: 0,
                            stroke: "var(--chart-2)",
                            strokeWidth: 2.25,
                        }),
                    ],
                    scales: {
                        x: {
                            scale: scaleLinear().domain([40, 220]),
                            grid: true,
                            axis: {
                                line: false,
                                label: "Engine Power (hp)",
                                ticks: { size: 0 },
                            },
                        },
                        y: {
                            scale: scaleLinear().domain([5, 50]),
                            grid: true,
                            axis: {
                                line: false,
                                label: "Fuel Economy (mpg)",
                                ticks: { size: 0 },
                            },
                        },
                    },
                    margin: { top: 24, right: 24, bottom: 32, left: 45 },
                    theme: {
                        foreground: "var(--muted-foreground)",
                        grid: "var(--border)",
                        background: "transparent",
                    },
                },
                {
                    focus: "group-x",
                    tooltip: {
                        use: tooltip,
                        className:
                            "font-sans shadow-none rounded-md bg-popover text-popover-foreground border p-2 text-xs",
                        anchor: "group-center",
                        placement: "auto",
                        content: (points) => shadcnTooltipContent(points),
                    },
                },
            ),
        [data],
    );

    return (
        <Card className="w-full max-w-xl">
            <CardHeader>
                <CardTitle>Horsepower vs Fuel Economy</CardTitle>
                <CardDescription>Scatterplot with fitted linear regression trend line</CardDescription>
            </CardHeader>
            <CardContent>
                <div className="h-[250px] w-full">
                    <Chart
                        definition={definition}
                        renderer={motionRenderer}
                        height={250}
                        ariaLabel="Horsepower vs Fuel Economy Chart"
                    />
                </div>
            </CardContent>
            <CardFooter className="flex-col items-start gap-2 text-sm">
                <div className="flex items-center gap-2 leading-none font-medium">
                    Strong negative correlation observed between horsepower and MPG{" "}
                    <TrendingDown className="h-4 w-4 text-rose-500" />
                </div>
                <div className="text-muted-foreground leading-none">
                    Red line denotes ordinary least squares linear fit estimate
                </div>
            </CardFooter>
        </Card>
    );
}

export default LinearRegressionChart;
```
