# Chart

Zenos design-system helpers around Recharts primitives.

Zenos design-system helpers around Recharts primitives.

<p className="zenos-recipe-source">
  Powered by <a href="https://recharts.org/">Recharts</a> for chart geometry and rendering. Zenos
  owns configuration metadata, semantic variables, tooltip and legend presentation, and container
  behavior.
</p>

```bash
pnpm dlx @zentara-co/zenos-cli add chart
npx @zentara-co/zenos-cli add chart
yarn dlx @zentara-co/zenos-cli add chart
bunx @zentara-co/zenos-cli add chart
```

The command installs Recharts and adds the chart helpers to the consumer project. Import Zenos helpers from the installed recipe and geometry primitives from Recharts:

```tsx
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from "./components/chart";
```

Recharts owns geometry and rendering. Zenos owns `ChartContainer`, `ChartConfig`, `ChartTooltip`, `ChartTooltipContent`, `ChartLegend`, `ChartLegendContent`, semantic series variables, and design-system presentation.

## Bar chart

Use bars when readers need to compare discrete categories or time buckets. Keep the zero baseline visible when magnitude is the primary comparison.

```tsx
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@docs/src/recipes/chart/chart";

const chartData = [
  { month: "Jan", findings: 18 },
  { month: "Feb", findings: 12 },
  { month: "Mar", findings: 16 },
  { month: "Apr", findings: 8 },
  { month: "May", findings: 11 },
  { month: "Jun", findings: 6 },
];

const chartConfig = {
  findings: { label: "Open findings", color: "var(--chart-1)" },
} satisfies ChartConfig;

function ChartRecipeExample() {
  return (
    <div className="w-full max-w-2xl">
      <ChartContainer config={chartConfig} aria-label="Open findings by month" className="max-h-72">
        <BarChart data={chartData} accessibilityLayer>
          <CartesianGrid vertical={false} />
          <XAxis dataKey="month" tickLine={false} axisLine={false} />
          <ChartTooltip content={<ChartTooltipContent />} />
          <Bar dataKey="findings" fill="var(--color-findings)" radius={[4, 4, 0, 0]} />
        </BarChart>
      </ChartContainer>
    </div>
  );
}
```

```tsx
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from "./components/chart";

const config = {
  revenue: { label: "Revenue", color: "var(--chart-1)" },
} satisfies ChartConfig;

<ChartContainer config={config} aria-label="Monthly revenue">
  <BarChart data={data}>
    <CartesianGrid vertical={false} />
    <XAxis dataKey="month" />
    <ChartTooltip content={<ChartTooltipContent />} />
    <Bar dataKey="revenue" fill="var(--color-revenue)" />
  </BarChart>
</ChartContainer>;
```

## Stacked bar chart

Stacked bars show a total and its composition at the same time. Use them when the combined height matters and the segments share the same unit.

```tsx
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
import { ChartContainer, ChartLegend, ChartLegendContent, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@docs/src/recipes/chart/chart";

const responseData = [
  { team: "Identity", withinSla: 18, breached: 4 },
  { team: "Platform", withinSla: 24, breached: 7 },
  { team: "Data", withinSla: 16, breached: 3 },
  { team: "Web", withinSla: 21, breached: 5 },
];

const responseConfig = {
  withinSla: { label: "Within SLA", color: "var(--chart-2)" },
  breached: { label: "Breached", color: "var(--chart-5)" },
} satisfies ChartConfig;

function ChartStackedBarExample() {
  return (
    <div className="w-full max-w-2xl">
      <ChartContainer
        config={responseConfig}
        aria-label="Incident response by team"
        className="h-72 aspect-auto"
      >
        <BarChart data={responseData} accessibilityLayer>
          <CartesianGrid vertical={false} />
          <XAxis dataKey="team" tickLine={false} axisLine={false} tickMargin={8} />
          <YAxis tickLine={false} axisLine={false} width={32} />
          <ChartTooltip content={<ChartTooltipContent indicator="line" />} />
          <ChartLegend content={<ChartLegendContent />} />
          <Bar dataKey="withinSla" stackId="response" fill="var(--color-withinSla)" />
          <Bar
            dataKey="breached"
            stackId="response"
            fill="var(--color-breached)"
            radius={[4, 4, 0, 0]}
          />
        </BarChart>
      </ChartContainer>
    </div>
  );
}
```

Give related `Bar` elements the same `stackId`. The example keeps the successful and breached portions in one column, adds a legend, and uses a line indicator in the tooltip. Prefer grouped bars when readers need precise side-by-side comparisons between segments.

## Line chart

Use lines for trends across an ordered dimension. This sentiment example follows the same structure as a production analytics chart: three related series, dashed horizontal and vertical grid lines, quiet axes, visible data points, and a larger active point.

```tsx
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts";
import { ChartContainer, ChartLegend, ChartLegendContent, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@docs/src/recipes/chart/chart";

const sentimentData = [
  { date: "Sep 1", positive: 38, neutral: 24, negative: 16 },
  { date: "Sep 2", positive: 44, neutral: 29, negative: 13 },
  { date: "Sep 3", positive: 41, neutral: 26, negative: 19 },
  { date: "Sep 4", positive: 52, neutral: 31, negative: 17 },
  { date: "Sep 5", positive: 48, neutral: 34, negative: 12 },
  { date: "Sep 6", positive: 57, neutral: 30, negative: 10 },
];

const sentimentConfig = {
  positive: { label: "Positive", color: "var(--chart-2)" },
  neutral: { label: "Neutral", color: "var(--chart-4)" },
  negative: { label: "Negative", color: "var(--chart-5)" },
} satisfies ChartConfig;

function ChartLineExample() {
  return (
    <div className="w-full max-w-2xl">
      <ChartContainer
        config={sentimentConfig}
        aria-label="News sentiment by date"
        className="h-72 aspect-auto"
      >
        <LineChart
          data={sentimentData}
          accessibilityLayer
          margin={{ top: 12, right: 12, bottom: 8, left: 0 }}
        >
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="date" tickLine={false} axisLine={false} tickMargin={8} />
          <YAxis tickLine={false} axisLine={false} tickMargin={8} width={36} />
          <ChartTooltip content={<ChartTooltipContent />} />
          <ChartLegend content={<ChartLegendContent />} />
          <Line
            dataKey="negative"
            type="monotone"
            stroke="var(--color-negative)"
            strokeWidth={2}
            dot={{ r: 3, fill: "var(--color-negative)", strokeWidth: 2 }}
            activeDot={{ r: 6 }}
          />
          <Line
            dataKey="neutral"
            type="monotone"
            stroke="var(--color-neutral)"
            strokeWidth={2}
            dot={{ r: 3, fill: "var(--color-neutral)", strokeWidth: 2 }}
            activeDot={{ r: 6 }}
          />
          <Line
            dataKey="positive"
            type="monotone"
            stroke="var(--color-positive)"
            strokeWidth={2}
            dot={{ r: 3, fill: "var(--color-positive)", strokeWidth: 2 }}
            activeDot={{ r: 6 }}
          />
        </LineChart>
      </ChartContainer>
    </div>
  );
}
```

The legend and tooltip both read labels and colors from the same `ChartConfig`, so Positive, Neutral, and Negative stay synchronized across the visualization and interaction content.

## Area chart

Area charts emphasize magnitude over time. The filled variant reuses the sentiment data and adds an independent vertical gradient beneath each series. The fill fades to transparent so overlapping values, grid lines, and tooltip cursor remain readable.

```tsx
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
import { ChartContainer, ChartLegend, ChartLegendContent, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@docs/src/recipes/chart/chart";

const sentimentData = [
  { date: "Sep 1", positive: 38, neutral: 24, negative: 16 },
  { date: "Sep 2", positive: 44, neutral: 29, negative: 13 },
  { date: "Sep 3", positive: 41, neutral: 26, negative: 19 },
  { date: "Sep 4", positive: 52, neutral: 31, negative: 17 },
  { date: "Sep 5", positive: 48, neutral: 34, negative: 12 },
  { date: "Sep 6", positive: 57, neutral: 30, negative: 10 },
];

const sentimentConfig = {
  positive: { label: "Positive", color: "var(--chart-2)" },
  neutral: { label: "Neutral", color: "var(--chart-4)" },
  negative: { label: "Negative", color: "var(--chart-5)" },
} satisfies ChartConfig;

function ChartAreaExample() {
  return (
    <div className="w-full max-w-2xl">
      <ChartContainer
        config={sentimentConfig}
        aria-label="Filled news sentiment trends by date"
        className="h-72 aspect-auto"
      >
        <AreaChart
          data={sentimentData}
          accessibilityLayer
          margin={{ top: 12, right: 12, bottom: 8, left: 0 }}
        >
          <defs>
            <linearGradient id="sentiment-positive-fill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor="var(--color-positive)" stopOpacity={0.3} />
              <stop offset="95%" stopColor="var(--color-positive)" stopOpacity={0} />
            </linearGradient>
            <linearGradient id="sentiment-neutral-fill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor="var(--color-neutral)" stopOpacity={0.3} />
              <stop offset="95%" stopColor="var(--color-neutral)" stopOpacity={0} />
            </linearGradient>
            <linearGradient id="sentiment-negative-fill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor="var(--color-negative)" stopOpacity={0.5} />
              <stop offset="95%" stopColor="var(--color-negative)" stopOpacity={0} />
            </linearGradient>
          </defs>
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="date" tickLine={false} axisLine={false} tickMargin={8} />
          <YAxis tickLine={false} axisLine={false} tickMargin={8} width={36} />
          <ChartTooltip content={<ChartTooltipContent />} />
          <ChartLegend content={<ChartLegendContent />} />
          <Area
            dataKey="negative"
            type="monotone"
            fill="url(#sentiment-negative-fill)"
            stroke="var(--color-negative)"
            strokeWidth={2}
            dot={{ r: 3, fill: "var(--color-negative)", strokeWidth: 2 }}
            activeDot={{ r: 6 }}
          />
          <Area
            dataKey="neutral"
            type="monotone"
            fill="url(#sentiment-neutral-fill)"
            stroke="var(--color-neutral)"
            strokeWidth={2}
            dot={{ r: 3, fill: "var(--color-neutral)", strokeWidth: 2 }}
            activeDot={{ r: 6 }}
          />
          <Area
            dataKey="positive"
            type="monotone"
            fill="url(#sentiment-positive-fill)"
            stroke="var(--color-positive)"
            strokeWidth={2}
            dot={{ r: 3, fill: "var(--color-positive)", strokeWidth: 2 }}
            activeDot={{ r: 6 }}
          />
        </AreaChart>
      </ChartContainer>
    </div>
  );
}
```

Define gradients inside the chart SVG and reference scoped `--color-{key}` variables. This keeps the presentation theme-aware without reading the active theme in application code.

## Interactive donut chart

Use a donut for a small part-to-whole dataset. The center summary should show the total by default and the active segment value during pointer exploration.

```tsx
import { useState } from "react";
import { Text } from "@zentara-co/zenos-ui";
import { Pie, PieChart } from "recharts";
import { ChartContainer, type ChartConfig } from "@docs/src/recipes/chart/chart";

const newsSourceData = [
  { key: "daily", name: "Daily Wire", total: 1280, color: "var(--chart-1)" },
  { key: "journal", name: "City Journal", total: 940, color: "var(--chart-2)" },
  { key: "dispatch", name: "The Dispatch", total: 720, color: "var(--chart-3)" },
  { key: "observer", name: "News Observer", total: 510, color: "var(--chart-4)" },
  { key: "others", name: "Others", total: 350, color: "var(--chart-5)" },
];

const newsSourceConfig = {
  daily: { label: "Daily Wire", color: "var(--chart-1)" },
  journal: { label: "City Journal", color: "var(--chart-2)" },
  dispatch: { label: "The Dispatch", color: "var(--chart-3)" },
  observer: { label: "News Observer", color: "var(--chart-4)" },
  others: { label: "Others", color: "var(--chart-5)" },
} satisfies ChartConfig;

function ChartInteractiveDonutExample() {
  const [activeIndex, setActiveIndex] = useState<number>();
  const activeSource = activeIndex === undefined ? undefined : newsSourceData[activeIndex];
  const totalNews = newsSourceData.reduce((total, source) => total + source.total, 0);
  const renderedSources = newsSourceData.map((source, index) => ({
    ...source,
    fill: source.color,
    opacity: activeIndex === undefined || activeIndex === index ? 1 : 0.45,
  }));

  return (
    <div className="flex w-full max-w-2xl flex-col items-center justify-center gap-6 sm:flex-row">
      <div className="relative size-64 shrink-0">
        <ChartContainer
          config={newsSourceConfig}
          aria-label="News articles by source"
          className="aspect-square size-full [&_.recharts-sector]:transition-opacity"
        >
          <PieChart accessibilityLayer>
            <Pie
              data={renderedSources}
              dataKey="total"
              nameKey="name"
              innerRadius={68}
              outerRadius={96}
              paddingAngle={4}
              cornerRadius={6}
              stroke="transparent"
              isAnimationActive={false}
              onMouseEnter={(_, index) => setActiveIndex(index)}
              onMouseLeave={() => setActiveIndex(undefined)}
            />
          </PieChart>
        </ChartContainer>
        <div
          aria-live="polite"
          className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center text-center"
        >
          <Text color="subtle" size="s" className="max-w-28 truncate">
            {activeSource?.name ?? "Total news"}
          </Text>
          <Text weight="bold" className="tabular-nums">
            {(activeSource?.total ?? totalNews).toLocaleString()}
          </Text>
        </div>
      </div>
      <div className="grid grid-cols-2 gap-x-5 gap-y-3">
        {newsSourceData.map((source) => (
          <div key={source.key} className="flex min-w-0 items-center gap-2">
            <span
              aria-hidden="true"
              className="size-2.5 shrink-0 rounded-full"
              style={{ backgroundColor: source.color }}
            />
            <Text size="s" className="truncate">
              {source.name}
            </Text>
          </div>
        ))}
      </div>
    </div>
  );
}
```

The example groups smaller publishers into “Others,” dims inactive sectors on hover, updates the center label through a polite live region, and keeps the legend outside the SVG so long labels can truncate predictably. For more than five or six categories, prefer a sorted bar chart.

## Radar chart

Radar charts compare several dimensions that share a meaningful scale. They work best for a small profile such as current posture against a target, not for ranking unrelated values.

```tsx
import { PolarAngleAxis, PolarGrid, Radar, RadarChart } from "recharts";
import { ChartContainer, ChartLegend, ChartLegendContent, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@docs/src/recipes/chart/chart";

const postureData = [
  { control: "Identity", current: 86, target: 92 },
  { control: "Devices", current: 74, target: 88 },
  { control: "Network", current: 82, target: 90 },
  { control: "Data", current: 69, target: 84 },
  { control: "Recovery", current: 77, target: 86 },
];

const postureConfig = {
  current: { label: "Current", color: "var(--chart-1)" },
  target: { label: "Target", color: "var(--chart-3)" },
} satisfies ChartConfig;

function ChartRadarExample() {
  return (
    <div className="w-full max-w-lg">
      <ChartContainer
        config={postureConfig}
        aria-label="Security posture by control family"
        className="h-80 aspect-auto"
      >
        <RadarChart data={postureData} accessibilityLayer outerRadius="68%">
          <PolarGrid />
          <PolarAngleAxis dataKey="control" tickLine={false} />
          <ChartTooltip content={<ChartTooltipContent />} />
          <ChartLegend content={<ChartLegendContent />} />
          <Radar
            dataKey="target"
            fill="var(--color-target)"
            fillOpacity={0.12}
            stroke="var(--color-target)"
            strokeDasharray="4 4"
            strokeWidth={2}
          />
          <Radar
            dataKey="current"
            fill="var(--color-current)"
            fillOpacity={0.25}
            stroke="var(--color-current)"
            strokeWidth={2}
          />
        </RadarChart>
      </ChartContainer>
    </div>
  );
}
```

Keep every axis on the same domain, limit the number of dimensions, and distinguish overlapping polygons with both stroke style and fill opacity. Include a legend because the shapes overlap.

## Radial progress chart

Use a radial bar for a single bounded value when the compact visual is more useful than a standard progress bar. Always repeat the exact value as text.

```tsx
import { Text } from "@zentara-co/zenos-ui";
import { PolarRadiusAxis, RadialBar, RadialBarChart } from "recharts";
import { ChartContainer, type ChartConfig } from "@docs/src/recipes/chart/chart";

const remediationData = [{ name: "Resolved", value: 76, fill: "var(--color-resolved)" }];

const remediationConfig = {
  resolved: { label: "Resolved", color: "var(--chart-2)" },
} satisfies ChartConfig;

function ChartRadialExample() {
  return (
    <div className="relative size-64">
      <ChartContainer
        config={remediationConfig}
        aria-label="76 percent of findings resolved"
        className="aspect-square size-full"
      >
        <RadialBarChart
          data={remediationData}
          innerRadius={76}
          outerRadius={104}
          startAngle={90}
          endAngle={-270}
          accessibilityLayer
        >
          <PolarRadiusAxis domain={[0, 100]} tick={false} axisLine={false} />
          <RadialBar dataKey="value" background cornerRadius={12} isAnimationActive={false} />
        </RadialBarChart>
      </ChartContainer>
      <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
        <Text weight="bold" className="text-2xl tabular-nums">
          76%
        </Text>
        <Text color="subtle" size="s">
          Resolved
        </Text>
      </div>
    </div>
  );
}
```

The visible `76%` is the primary value; the arc is supporting context. Set the radius axis domain explicitly so the chart represents the full 0–100 range.

## Choosing a chart

- Use bars for comparison across categories and stacked bars for composition within a total.
- Use lines for change over an ordered interval and areas when magnitude is also important.
- Use a donut only for a short part-to-whole breakdown.
- Use radar for a compact multidimensional profile with a shared scale.
- Use radial progress for one bounded metric. Use the Progress component when space, precision, or familiarity matters more than visual emphasis.

## Preparing data

Keep data shaping outside the chart markup. Convert timestamps, group small categories, calculate percentages, and supply fallback zeroes before rendering. Each row should have a stable category key and numeric values for every visible series.

For asynchronous data, render loading, empty, and error states around `ChartContainer`. Do not render an empty SVG as the only explanation. A useful empty state names the missing dataset and, when possible, the filter or date range that produced it.

## Configuration and colors

The recipe uses `--chart-1` through `--chart-5`, plus grid, axis, and tooltip roles. The CLI only inserts missing tokens.

Each config key should match a Recharts `dataKey`. `ChartContainer` maps its color to a scoped `--color-{key}` variable:

```tsx
const config = {
  organic: { label: "Organic", color: "var(--chart-1)" },
  referral: { label: "Referral", color: "var(--chart-2)" },
} satisfies ChartConfig;
```

Use the scoped variables inside series so the same component responds to theme tokens without branching on the active theme.

## Tooltips and legends

`ChartTooltipContent` supports `dot`, `line`, and `dashed` indicators. Use `valueFormatter` for units, currency, percentages, or domain-specific formatting. Use `labelFormatter` when the axis label needs a readable date or period.

`ChartLegendContent` resolves the same labels and optional icons from `ChartConfig`. Set `hideIcon` only when series names remain distinguishable without a color marker.

## Axes and grids

Remove axis and tick lines when the grid already establishes the scale. Use `tickMargin` to separate labels from the plot and reserve enough `YAxis` width for the longest formatted value. Dashed grids suit dense analytical views; fewer or horizontal-only lines keep simple comparison charts quieter.

Format dates and compact numbers at the axis boundary, but preserve exact values in the tooltip or a nearby data table.

## Responsive sizing

ChartContainer uses a responsive Recharts container and defaults to a video aspect ratio. Override its height or aspect ratio at the composition site:

```tsx
<ChartContainer config={config} className="h-72 aspect-auto" aria-label="Monthly revenue">
  <BarChart data={data}>{/* ... */}</BarChart>
</ChartContainer>
```

Give a chart an explicit height when it sits inside a grid or resizable panel. Avoid relying on percentage height when no ancestor establishes a height.

## Motion and performance

Keep animation brief and avoid replaying it after every hover or parent render. Disable nonessential animation for frequently updating dashboards and respect the user's reduced-motion preference. For large datasets, reduce the number of visible points, aggregate by an appropriate interval, and avoid expensive custom SVG renderers on every mark.

## Testing

Test the information and interaction contract rather than Recharts internals. Assert the chart's accessible name, legend labels, formatted tooltip values, filters, and any live summaries. Avoid depending on generated SVG path data or element order, which can change between rendering-engine versions.

## Accessibility

- Add `aria-label` or `aria-labelledby` to ChartContainer.
- Enable Recharts `accessibilityLayer` for keyboard-readable Cartesian and polar charts.
- Provide a nearby text summary or data table when exact values are essential.
- Do not encode meaning with color alone; use labels, legends, line styles, or direct annotations.
- Announce changing center summaries only when the interaction communicates useful information.
- Respect reduced motion when adding series or number animations.

Use Recharts directly for axes, grids, series, reference geometry, and interaction callbacks. The recipe intentionally does not hide those capabilities behind a large chart prop API.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| config | ChartConfig | — | Series labels, colors, icons, and semantic metadata. |
| children | ReactElement | — | A Recharts chart primitive. |
| content | ReactElement | — | Custom content supplied to ChartTooltip or ChartLegend. |
| hideLabel / hideIndicator | boolean | false | Tooltip density controls. |
| indicator | 'dot' \| 'line' \| 'dashed' | dot | Tooltip series marker. |
| nameKey / labelKey | string | — | Metadata lookup keys. |

Source: https://zenos-ui.pages.dev/recipes/chart/