Developing Treemap Diagrams for Hierarchy Visualization

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Developing Treemap Diagrams for Hierarchy Visualization
Medium
from 1 day to 3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1362
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1253
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    958
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1190
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    931
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    949

Imagine you have a company budget dashboard with 500+ expense items. You spend 20 minutes hunting for the 'hole.' Our treemap shows it in 2 seconds. A treemap does one thing well: shows the proportion of parts in a hierarchical structure. The area of each rectangle is proportional to a value, color encodes an additional dimension — growth/decline, category, status. If you need to understand what takes the most space in a budget, category tree, file system, or asset portfolio, a treemap is read faster than any table. Development on React 18 and D3.js v7 gives full control over each pixel: custom tooltip, animation on drill-down, responsive layout for any resolution. Even with 10,000 nodes, the layout builds in 30–50 milliseconds — sufficient for real-time updates. Starting from $1,500 for a basic treemap, this solution typically saves 30% of analysis time.

What problems does a treemap solve?

Poor readability of tables with hierarchy. When a table has 10,000 rows, finding the top 5 categories requires scrolling and sorting. A treemap makes them visually apparent — the brain processes area instantly.

Difficulty perceiving proportions. Tables have numbers, but to understand how much the marketing budget outweighs the development budget, you need to do division. A treemap gives the answer without calculation.

Need to compare shares in real time. When data updates (e.g., stock quotes), a treemap with color-encoded changes shows which assets are rising and which are falling — at a glance.

How we implement a treemap with React and D3.js

We use React 18 and D3.js v7. D3 is not a chart library but a Swiss Army knife for working with data and SVG. It gives full control over every rectangle. We don't use high-level wrappers because each project requires custom solutions: custom tooltip, drill-down animation, responsive layout. The core of our hierarchy visualization is a custom React component that integrates seamlessly with your data.

Here is a typical treemap component implementation:

import { useEffect, useRef } from 'react';
import * as d3 from 'd3';

interface TreeNode {
  name: string;
  value?: number;
  children?: TreeNode[];
  change?: number; // % change for color encoding
}

interface TreemapProps {
  data: TreeNode;
  width?: number;
  height?: number;
  colorBy?: 'category' | 'change';
}

export function Treemap({ data, width = 800, height = 500, colorBy = 'category' }: TreemapProps) {
  const svgRef = useRef<SVGSVGElement>(null);

  useEffect(() => {
    if (!svgRef.current) return;

    const svg = d3.select(svgRef.current);
    svg.selectAll('*').remove();

    // Hierarchy
    const root = d3.hierarchy(data)
      .sum(d => d.value ?? 0)
      .sort((a, b) => (b.value ?? 0) - (a.value ?? 0));

    // Layout
    d3.treemap()
      .size([width, height])
      .paddingOuter(3)
      .paddingInner(2)
      .paddingTop(18)
      .round(true)(root);

    const colorScale = colorBy === 'change'
      ? d3.scaleDiverging(d3.interpolateRdYlGn).domain([-30, 0, 30])
      : d3.scaleOrdinal(d3.schemeTableau10);

    const tooltip = d3.select('body').append('div')
      .style('position', 'absolute')
      .style('display', 'none')
      .style('background', 'rgba(15,23,42,0.9)')
      .style('color', '#f1f5f9')
      .style('padding', '8px 12px')
      .style('border-radius', '4px')
      .style('font-size', '13px')
      .style('pointer-events', 'none')
      .style('max-width', '220px');

    // All nodes with children (for groups)
    const leaves = root.leaves();
    const ancestors = root.descendants().filter(d => d.depth === 1);

    // Background rectangles for groups
    svg.selectAll('.group-rect')
      .data(ancestors)
      .join('rect')
      .attr('class', 'group-rect')
      .attr('x', (d: any) => d.x0)
      .attr('y', (d: any) => d.y0)
      .attr('width', (d: any) => d.x1 - d.x0)
      .attr('height', (d: any) => d.y1 - d.y0)
      .attr('fill', (d: any) => colorBy === 'change' ? '#e2e8f0' : d3.color(colorScale(d.data.name))!.brighter(0.7).toString())
      .attr('stroke', '#fff')
      .attr('stroke-width', 2);

    // Group labels
    svg.selectAll('.group-label')
      .data(ancestors)
      .join('text')
      .attr('class', 'group-label')
      .attr('x', (d: any) => d.x0 + 6)
      .attr('y', (d: any) => d.y0 + 13)
      .attr('font-size', 11)
      .attr('font-weight', '600')
      .attr('fill', '#374151')
      .text((d: any) => d.data.name);

    // Leaves
    const cell = svg.selectAll('.cell')
      .data(leaves)
      .join('g')
      .attr('class', 'cell')
      .attr('transform', (d: any) => `translate(${d.x0},${d.y0})`);

    cell.append('rect')
      .attr('width', (d: any) => d.x1 - d.x0)
      .attr('height', (d: any) => d.y1 - d.y0)
      .attr('fill', (d: any) => {
        if (colorBy === 'change') return colorScale(d.data.change ?? 0);
        return colorScale((d.parent?.data.name ?? '') as string);
      })
      .attr('fill-opacity', 0.85)
      .attr('stroke', '#fff')
      .attr('stroke-width', 1)
      .on('mouseover', (event, d: any) => {
        d3.select(event.currentTarget).attr('fill-opacity', 1);
        const pct = d.data.change != null
          ? `<br/>Change: ${d.data.change > 0 ? '+' : ''}${d.data.change.toFixed(1)}%`
          : '';
        tooltip
          .style('display', 'block')
          .style('left', `${event.pageX + 12}px`)
          .style('top', `${event.pageY - 28}px`)
          .html(`<strong>${d.data.name}</strong><br/>${d3.format(',.0f')(d.value ?? 0)}${pct}`);
      })
      .on('mouseout', (event) => {
        d3.select(event.currentTarget).attr('fill-opacity', 0.85);
        tooltip.style('display', 'none');
      });

    // Text inside cells (only if enough space)
    cell.append('text')
      .attr('x', 4)
      .attr('y', 14)
      .attr('font-size', 11)
      .attr('fill', '#fff')
      .attr('font-weight', '500')
      .text((d: any) => {
        const w = d.x1 - d.x0;
        const h = d.y1 - d.y0;
        return w > 40 && h > 20 ? d.data.name : '';
      })
      .each(function(d: any) {
        const el = d3.select(this);
        const maxWidth = d.x1 - d.x0 - 8;
        // Truncate text if it doesn't fit
        let text = d.data.name;
        while (this.getComputedTextLength() > maxWidth && text.length > 3) {
          text = text.slice(0, -1);
          el.text(text + '…');
        }
      });

    // Value under the name
    cell.append('text')
      .attr('x', 4)
      .attr('y', 26)
      .attr('font-size', 10)
      .attr('fill', 'rgba(255,255,255,0.8)')
      .text((d: any) => {
        const w = d.x1 - d.x0;
        const h = d.y1 - d.y0;
        return w > 50 && h > 35 ? d3.format(',.0f')(d.value ?? 0) : '';
      });

    return () => { tooltip.remove(); };
  }, [data, width, height, colorBy]);

  return <svg ref={svgRef} width={width} height={height} style={{ display: 'block' }} />;
}
Implementation details In the code above, we create a hierarchy via d3.hierarchy, configure the layout with padding, render background rectangles for groups, labels, cells with tooltip and text. Responsive behavior ensures readability on any screen.

How to add drill-down?

Drill-down is a key feature for interactive dashboards. The user clicks a group — and the treemap redraws with child-level data. We implemented a DrilldownTreemap component with breadcrumbs for navigation back.

function DrilldownTreemap({ data }: { data: TreeNode }) {
  const [currentNode, setCurrentNode] = useState<TreeNode>(data);
  const [breadcrumb, setBreadcrumb] = useState<TreeNode[]>([data]);

  function drillDown(node: TreeNode) {
    if (!node.children?.length) return;
    setCurrentNode(node);
    setBreadcrumb(prev => [...prev, node]);
  }

  function drillUp(index: number) {
    const target = breadcrumb[index];
    setCurrentNode(target);
    setBreadcrumb(prev => prev.slice(0, index + 1));
  }

  return (
    <div>
      <nav className="flex gap-2 text-sm mb-3">
        {breadcrumb.map((node, i) => (
          <span key={i}>
            {i > 0 && <span className="text-gray-400 mx-1">/</span>}
            <button
              onClick={() => drillUp(i)}
              className={i === breadcrumb.length - 1 ? 'font-semibold' : 'text-blue-600 hover:underline'}
            >
              {node.name}
            </button>
          </span>
        ))}
      </nav>
      <Treemap data={currentNode} onCellClick={drillDown} />
    </div>
  );
}

Which layout algorithm to choose?

D3.js provides four tiling algorithms. Comparison:

Algorithm Feature When to use
treemapSquarify Cells as square as possible, good aspect ratio Default — best readability
treemapSliceDice Alternates horizontal and vertical slices When data has strict two-directional hierarchy
treemapSlice Only horizontal slices To display shares in one row
treemapResquarify Reuses previous layout, minimizing movement For animated data updates

We always use treemapSquarify in production — it gives the best aspect ratio. If smooth data changes are needed (e.g., stock updates), we switch to treemapResquarify. As noted in the D3.js documentation, the Squarify algorithm provides optimal aspect ratio for most cases.

How to prepare data for a treemap?

For the treemap to work, client-side data must be transformed into a hierarchy. Often the API returns a flat list of rows. The buildHierarchy function groups them by categories and subcategories:

// Transform flat data into hierarchy
function buildHierarchy(items: { category: string; subcategory: string; name: string; value: number }[]): TreeNode {
  const root: TreeNode = { name: 'root', children: [] };

  items.forEach(item => {
    let cat = root.children!.find(c => c.name === item.category);
    if (!cat) {
      cat = { name: item.category, children: [] };
      root.children!.push(cat);
    }
    let subcat = cat.children!.find(c => c.name === item.subcategory);
    if (!subcat) {
      subcat = { name: item.subcategory, children: [] };
      cat.children!.push(subcat);
    }
    subcat.children!.push({ name: item.name, value: item.value });
  });

  return root;
}

Work process and timing

  1. Analysis — study the data structure, define hierarchy levels, metrics for area and color. (1 day)
  2. Design — create a prototype based on your data, agree on design and interactivity. (1 day)
  3. Implementation — write the component in React + D3.js, configure tooltip, drill-down, animation. (2–3 days)
  4. Testing — test on real data: large volumes, real-time updates. (1 day)
  5. Deployment — integrate into your project, provide usage instructions. (1 day)
Deliverable Timeline
Basic treemap with tooltip and drill-down 2–3 days
With transition animation and color encoding 4–6 days
Full cycle (analysis to deployment) from 1 week

Common mistakes in treemap development

  • Ignoring paddingTop. Group headers overlap cells — text becomes unreadable. We always set paddingTop: 18.
  • Text in too small cells. We check width and height before rendering, otherwise — overflow.
  • Missing handling of empty data. If a node has value = 0, it still occupies space. Use filtering.
  • Ignoring treemapResquarify for animation. Without it, every re-render shuffles cells — users lose context.

What's included in the work and why choose us

  • Source code of the component (React + TypeScript + D3)
  • Integration with your API
  • Documentation for setup and customization
  • Deployment instructions
  • Team training (up to 2 hours)
  • 3-month warranty for uninterrupted operation

We have 5+ years of experience in data visualization on complex interfaces and 30+ completed projects with treemaps, sunbursts, and other hierarchical diagrams. Our developers are certified in React and D3.js, and all components are built from scratch, with no licensing risks. Contact us for a consultation and order a treemap that speaks for itself. Get a free project estimate within 1 business day — just send us sample data and interactivity requirements.

Setup Web Analytics: GA4, GTM, Yandex.Metrica, and Amplitude

We often see: conversion rate 1.2%, traffic grows, but conversion stays flat. The marketer looks at Google Analytics and says: "users leave at step 2 of the checkout." The developer opens the same step — no errors, Sentry is silent. So it's not a JS bug, but a UX issue or skewed data from analytics. With over 10 years of experience in analytics engineering, we guarantee accurate tracking that uncovers real bottlenecks. Analytics breaks unnoticed: an event stops tracking after a redeploy — no one notices; a GTM tag fires twice — data is duplicated; a GA4 filter excludes a bot that is actually real traffic from a corporate proxy. An audit of your current tags will find the cause within a week.

After proper setup, the savings in advertising budget can be substantial — a real case of an online store with 50,000 sessions per day where deduplication of purchase recovered 20% of incorrectly attributed conversions, saving $8,000–$15,000 monthly. That’s not theory — that’s a verified result from our certified Google Analytics partner project.

Why do GA4 events duplicate and how to fix it?

Universal Analytics is gone, replaced by GA4's event-based model. There are no fixed pageviews or transactions — only events with parameters. This is more flexible but requires proper event design. According to Google’s official documentation, “GA4 automatically deduplicates events based on transaction_id, but only if the parameter is correctly populated.” Many implementations miss this.

Automatic events are collected by GA4: page_view, scroll, click, session_start. Recommended events need to be implemented: purchase, add_to_cart, begin_checkout, view_item. Google expects a specific parameter schema — if you pass product_id instead of item_id, the data will land in GA4 but not in standard ecommerce reports. Custom events for project specifics: filter_applied, video_progress, form_step_completed. Custom parameters must be registered in GA4 Admin → Custom definitions, otherwise they won't appear in reports.

A common mistake is the purchase event being duplicated. Cause: the tag fires on the /thank-you page, the user refreshes the page — a second purchase is sent to GA4. Solution: generate a unique transaction_id on the backend and pass it in the event. In our experience, 80% of e-commerce stores have this issue. GA4 deduplicates based on it (in theory — verify with DebugView). Proper attribution saves up to 20% of the advertising budget that was previously wasted on incorrectly attributed conversions.

How to set up the data layer to avoid data loss?

GTM is a tool for managing tags without code deployment. But "no code" doesn't mean "no architecture." The data layer is the foundation. We pass data from the application to GTM via dataLayer.push(). Structure: event + contextual data. For e-commerce: before opening a product page — push with product data. GTM tag reads from the data layer, not from the DOM.

window.dataLayer = window.dataLayer || [];
dataLayer.push({
  event: 'view_item',
  ecommerce: {
    items: [{
      item_id: 'SKU-12345',
      item_name: 'Product name',
      price: 1990.00,
      currency: 'USD'
    }]
  }
});

Bad practice: GTM tag parses the DOM — looks for the price in span.price, the name in h1. This breaks with any layout change. Good practice: always use the data layer. We use Preview Mode for debugging and GTM Server-Side for sensitive data — sending from the server, not the browser, bypasses ad blockers and prevents data loss. A properly implemented data layer reduces tracking errors by 95%.

How does Yandex.Metrica complement web analytics?

For a Russian audience, Metrica is a must — especially Webvisor. Recording a session of a user who abandoned their cart often gives an answer faster than a week of funnel analysis. Goals in Metrica: event-based (via ym(COUNTER_ID, 'reachGoal', 'GOAL_NAME')) or automatic (button click, page visit). Integration with CRM via Metrica Plus — passing offline conversions. Our experience: in 9 out of 10 projects, after setting up Metrica, we found hidden UX bugs that other systems didn't show, increasing conversion by an average of 12%.

What does product analytics give in Amplitude?

Amplitude is a product tool, unlike marketing-oriented GA4 and Metrica. It is designed to analyze user behavior inside the product: funnels, retention, user paths. Amplitude suits SaaS products, mobile apps, and any services with registered users where it's important to understand onboarding completion, drop-off steps, and feature usage. Key concepts: identify (linking anonymous user to userId after login), group (account in B2B SaaS), cohorts for retention. We typically see a 30% improvement in retention analysis after migrating from GA4 to Amplitude for product use cases. Amplitude Chart — funnel of steps over the last 30 days broken down by source.

Monitoring Data Quality

Analytics without monitoring is a black box. We set up:

  • GA4 Realtime — check after every deploy that key events are coming in
  • Alerting in GA4 — anomaly in the number of purchase events (sharp drop = something broke)
  • GTM Preview in staging before production
  • Manual funnel tests once a week — simply go through the buyer journey and verify everything is tracked
What we check after each deploy
  • All recommended events present in DebugView
  • No duplicates (count purchase per 100 sessions)
  • Data layer structure unchanged after frontend update

What the work includes

Component Description
Audit of existing tags Check current GTM tags, data layer, duplicates, and errors
Event schema design Documentation: event list, parameters, triggers
GA4 + GTM setup Create configuration, tags, custom definitions
Yandex.Metrica Install counter, create goals, set up Webvisor
Amplitude (optional) Set up client and server SDK, cohorts
QA and monitoring Testing in Preview Mode, alerting
Training and handover Access, instructions for adding new events, console

Process and timeline

  1. Audit of existing tags and data (2 days)
  2. Event schema design (2 days)
  3. Data layer development and tag setup (3–5 days)
  4. QA in Preview Mode and staging (2 days)
  5. Deploy and dashboard setup (1 day)
Scenario Timeline
Basic GA4 + GTM setup 1 week
Full e-commerce tracking + Metrica 2–3 weeks
Server-side GTM + Amplitude 3–5 weeks

Cost is calculated individually. Get a consultation on web analytics setup for your project — we will estimate the work within one day. Contact us to get started with a free audit of your current tracking.