# Grouped Reducer Bars

> Grouped dataset aggregation calculating mean values per category.

A shadcn/ui block from the [@pacekit](https://ui.pacekit.dev/?utm_source=shadcn.exchange) registry, listed on [shadcn.exchange](https://shadcn.exchange/r/pacekit/tanstack-charts-grouped-reducer-bars).

- Page, with a live preview: https://shadcn.exchange/r/pacekit/tanstack-charts-grouped-reducer-bars
- Screenshot: https://abzjhwgwpdpz7ua5.public.blob.vercel-storage.com/shots/pacekit/tanstack-charts-grouped-reducer-bars-light-cefa4990942c2874.png
- Registry item: https://ui.pacekit.dev/r/tanstack-charts-grouped-reducer-bars.json
- Listed: 2026-10-21, source last changed 2026-10-21

## Install

```bash
npx shadcn@latest add https://shadcn.exchange/r/pacekit/tanstack-charts-grouped-reducer-bars.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/bar/grouped-reducer-bars.tsx`

```tsx
import { type ChartPoint, barY, defineChart, groupBy, text } 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 { scaleBand, scaleLinear } from "d3-scale";
import { BarChart2 } from "lucide-react";

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

interface RawObservation {
    species: string;
    body_mass_g: number;
}

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

function generateDemoData(): RawObservation[] {
    const results: RawObservation[] = [];
    const species = ["Adelie", "Chinstrap", "Gentoo"];
    const means = [3700, 3730, 5080];

    species.forEach((sp, idx) => {
        for (let i = 0; i < 40; i++) {
            results.push({
                species: sp,
                body_mass_g: means[idx] + (Math.random() - 0.5) * 600,
            });
        }
    });

    return results;
}

function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
    if (points.length === 0) return { title: "", rows: [] };
    const d = points[0].datum as { species: string; meanBodyMass: number };
    if (!d) return { title: "", rows: [] };
    return {
        title: d.species,
        rows: [
            {
                label: "Mean Body Mass",
                value: `${Math.round(d.meanBodyMass).toLocaleString()} g`,
                color: "var(--chart-1)",
            },
        ],
    };
}

export function GroupedReducerBars() {
    const rawData = useMemo(() => generateDemoData(), []);

    const aggregatedRows = useMemo(() => {
        return groupBy(rawData, {
            by: "species",
            outputs: {
                meanBodyMass: { value: "body_mass_g", reduce: "mean" },
            },
        });
    }, [rawData]);

    const definition = useMemo(
        () =>
            defineChart(
                {
                    renderer: motionRenderer,
                    marks: [
                        barY(aggregatedRows, {
                            x: "species",
                            y: "meanBodyMass",
                            fill: "var(--chart-1)",
                            inset: 2,
                            radius: 4,
                        }),
                        text(aggregatedRows, {
                            x: "species",
                            y: "meanBodyMass",
                            text: (row: { meanBodyMass: number }) =>
                                `${Math.round(row.meanBodyMass).toLocaleString()} g`,
                            fill: "var(--foreground)",
                            dy: -10,
                            fontSize: 11,
                            fontWeight: 600,
                        }),
                    ],
                    scales: {
                        x: {
                            scale: () => scaleBand<string>().paddingInner(0.3).paddingOuter(0.1),
                        },
                        y: {
                            scale: scaleLinear,
                            grid: true,
                            axis: { label: "Mean Body Mass (g)" },
                        },
                    },
                    margin: { top: 28, right: 24, bottom: 32, left: 45 },
                    theme: {
                        foreground: "var(--muted-foreground)",
                        grid: "var(--border)",
                        background: "transparent",
                    },
                },
                {
                    keyboard: true,
                    tooltip: {
                        use: tooltip,
                        className:
                            "font-sans shadow-none rounded-md bg-popover text-popover-foreground border p-2 text-xs",
                        anchor: "pointer",
                        placement: "auto",
                        content: (points) => shadcnTooltipContent(points),
                    },
                },
            ),
        [aggregatedRows],
    );

    return (
        <Card className="w-full max-w-xl">
            <CardHeader>
                <CardTitle>Grouped Mean Aggregator Bars</CardTitle>
                <CardDescription>
                    Grouped dataset aggregation calculating mean values dynamically across species
                </CardDescription>
            </CardHeader>
            <CardContent>
                <div className="h-[250px] w-full">
                    <Chart
                        definition={definition}
                        renderer={motionRenderer}
                        height={250}
                        ariaLabel="Grouped Mean Aggregator Bars Chart"
                    />
                </div>
            </CardContent>
            <CardFooter className="flex-col items-start gap-2 text-sm">
                <div className="flex items-center gap-2 leading-none font-medium">
                    Gentoo displays 36% higher mean body mass than Adelie{" "}
                    <BarChart2 className="h-4 w-4 text-emerald-500" />
                </div>
                <div className="text-muted-foreground leading-none">
                    `groupBy` transform reduces raw observation rows into mean metric bars
                </div>
            </CardFooter>
        </Card>
    );
}

export default GroupedReducerBars;
```
