Bar Chart

Charts

Vertical bar chart with multiple datasets.

Preview

Jan40Feb65Mar55Apr80May72Jun90

Usage

example.jsx
import { BarChart } from "@/components/ui/bar-chart";

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

Source Code

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

bar-chart.jsx
"use client";

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

const BarChart = forwardRef(({ className, data = [], width = 400, height = 250, barColor = "var(--primary)", ...props }, ref) => {
  const maxVal = Math.max(...data.map((d) => d.value), 1);
  const barW = Math.max(20, (width - 60) / data.length - 8);

  return (
    <div ref={ref} className={cn("inline-block", className)} {...props}>
      <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
        {/* Y axis */}
        <line x1="40" y1="10" x2="40" y2={height - 30} stroke="currentColor" opacity="0.2" />
        {/* X axis */}
        <line x1="40" y1={height - 30} x2={width - 10} y2={height - 30} stroke="currentColor" opacity="0.2" />
        {data.map((d, i) => {
          const barH = (d.value / maxVal) * (height - 50);
          const x = 50 + i * ((width - 60) / data.length);
          const y = height - 30 - barH;
          return (
            <g key={i}>
              <rect x={x} y={y} width={barW} height={barH} fill={d.color || barColor} rx="2" opacity="0.85" />
              <text x={x + barW / 2} y={height - 14} textAnchor="middle" className="fill-muted-foreground text-[10px]">{d.label}</text>
              <text x={x + barW / 2} y={y - 4} textAnchor="middle" className="fill-foreground text-[10px]">{d.value}</text>
            </g>
          );
        })}
      </svg>
    </div>
  );
});
BarChart.displayName = "BarChart";

export { BarChart };

Quick Install

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

npm install clsx tailwind-merge