Area Chart

Charts

Filled area chart with gradient shading.

Preview

JanFebMarAprMayJun

Usage

example.jsx
import { AreaChart } from "@/components/ui/area-chart";

export default function Example() {
  return <AreaChart />;
}

Source Code

Copy this file into components/ui/area-chart.jsx in your project.

area-chart.jsx
"use client";

import { forwardRef } from "react";
import { cn } from "@/lib/utils";

const AreaChart = forwardRef(({ className, data = [], width = 400, height = 250, color = "var(--primary)", ...props }, ref) => {
  const maxVal = Math.max(...data.map((d) => d.value), 1);
  const padX = 50, padY = 20;
  const chartW = width - padX - 10;
  const chartH = height - padY * 2 - 10;

  const points = data.map((d, i) => ({
    x: padX + (i / (data.length - 1 || 1)) * chartW,
    y: padY + chartH - (d.value / maxVal) * chartH,
  }));

  const lineD = points.map((p, i) => `${i === 0 ? "M" : "L"}${p.x},${p.y}`).join(" ");
  const areaD = `${lineD} L${points[points.length - 1]?.x || padX},${padY + chartH} L${padX},${padY + chartH} Z`;

  return (
    <div ref={ref} className={cn("inline-block", className)} {...props}>
      <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
        <defs>
          <linearGradient id="areaGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity="0.3" />
            <stop offset="100%" stopColor={color} stopOpacity="0.02" />
          </linearGradient>
        </defs>
        <path d={areaD} fill="url(#areaGrad)" />
        <path d={lineD} fill="none" stroke={color} strokeWidth="2" />
        {points.map((p, i) => (
          <text key={i} x={p.x} y={height - 8} textAnchor="middle" className="fill-muted-foreground text-[10px]">{data[i].label}</text>
        ))}
      </svg>
    </div>
  );
});
AreaChart.displayName = "AreaChart";

export { AreaChart };

Quick Install

Make sure you have the cn() utility set up. It requires clsx and tailwind-merge.

npm install clsx tailwind-merge