Treemap Chart

Charts

Treemap chart for hierarchical data visualization.

Preview

JavaScriptPythonTypeScript

Usage

example.jsx
import { TreemapChart } from "@/components/ui/treemap-chart";

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

Source Code

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

treemap-chart.jsx
"use client";

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

const COLORS = ["#6366f1", "#ec4899", "#f59e0b", "#10b981", "#3b82f6", "#8b5cf6", "#ef4444", "#06b6d4"];

const TreemapChart = forwardRef(({ className, data = [], width = 400, height = 300, ...props }, ref) => {
  const total = data.reduce((s, d) => s + d.value, 0) || 1;
  let x = 0;

  return (
    <div ref={ref} className={cn("inline-block", className)} {...props}>
      <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
        {data.map((d, i) => {
          const w = (d.value / total) * width;
          const rect = <g key={i}>
            <rect x={x} y={0} width={w} height={height} fill={d.color || COLORS[i % COLORS.length]} opacity="0.8" stroke="white" strokeWidth="2" />
            {w > 40 && <text x={x + w / 2} y={height / 2} textAnchor="middle" dominantBaseline="middle" className="fill-white text-xs font-medium">{d.label}</text>}
          </g>;
          x += w;
          return rect;
        })}
      </svg>
    </div>
  );
});
TreemapChart.displayName = "TreemapChart";

export { TreemapChart };

Quick Install

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

npm install clsx tailwind-merge