chartjs-chart-treemap

repository·main·Indexed 41 days ago

https://github.com/kurkle/chartjs-chart-treemap

A plugin for Chart.js (v3.8+ and v4+) that enables the creation of treemap charts to visualize hierarchical data through nested rectangles. It supports custom grouping, captions, data labels, and RTL layouts, requiring the registration of TreemapController and TreemapElement.

Tokens
9.5K
Snippets
28
Records
38
Agent score
99%

What's inside chartjs-chart-treemap

  1. Overview of chartjs-chart-treemap

    main
    chartjs-chart-treemap is a Chart.js module that adds a treemap chart type. It visualizes hierarchical (tree-structured) data as nested rectangles, where the area of each rectangle is proportional to its value. It is ideal for part-to-whole or hierarchical visualizations like disk usage, sales by category, or organizational structures.
  2. Handle missing hierarchy levels in treemap groups

    main

    When defining a treemap hierarchy using the groups option, you can include missing levels in your data. The treemap plugin automatically skips null, undefined, and empty group values. This allows a branch to continue directly to the next available group level without requiring a complete hierarchy for every data point.

    const data = [
      // 'component' and 'subFolder' are null, so the hierarchy skips directly from 'folder' to 'file'
      { folder: './src', component: null, subFolder: null, file: 'index.js', value: 6 },
      // 'subFolder' is null, so it skips from 'component' to 'file'
      { folder: './src', component: 'A', subFolder: null, file: 'A.js', value: 8 },
    ];
    
    const config = {
      type: 'treemap',
      data: {
        datasets: [{
          tree: data,
          key: 'value',
          groups: ['folder', 'component', 'subFolder', 'file'],
        }]
      }
    };
  3. Quickstart: Create a Treemap chart

    main

    To create a treemap, you must register the TreemapController and TreemapElement alongside the standard Chart.js registerables. Set the chart type to 'treemap' and provide your hierarchical data in the tree property within the dataset object.

    import { Chart, registerables } from 'chart.js';
    import { TreemapController, TreemapElement } from 'chartjs-chart-treemap';
    
    Chart.register(...registerables, TreemapController, TreemapElement);
    
    new Chart(document.getElementById('chart'), {
      type: 'treemap',
      data: {
        datasets: [
          {
            tree: [6, 6, 4, 3, 2, 2, 1],
            backgroundColor: 'rgba(54, 162, 235, 0.6)',
          },
        ],
      },
    });
  4. Configure the Zoom plugin for treemaps

    main

    To enable zooming and panning in a treemap chart, you must configure the zoom plugin within the options.plugins object. The plugin supports specific sub-configurations for zoom (e.g., enabling mouse wheel interaction) and pan (enabling dragging to move the view).

    const config = {
      type: 'treemap',
      data: {
        datasets: [
          {
            label: 'My First dataset',
            tree: Utils.numbers(NUMBER_CFG),
            // ... other dataset properties
          }
        ],
      },
      options: {
        plugins: {
          zoom: {
            zoom: {
              wheel: {
                enabled: true,
              }
            },
            pan: {
              enabled: true,
            }
          }
        }
      }
    };
  5. Configure the datalabels plugin in a treemap

    main

    To display data labels on a treemap, you must enable the datalabels plugin within the options.plugins configuration object. You can then customize the appearance and behavior of these labels within the specific dataset using the datalabels property.

    Key configuration options for datalabels include:

    • display: Controls visibility (e.g., 'auto' to hide labels that don't fit).
    • anchor: Sets the position relative to the chart element.
    • align: Sets the alignment angle.
    • formatter: A function to transform the raw value into a display string.
    • color: The color of the label text.
    • font: An object containing font properties like size.
    const config = {
      type: 'treemap',
      data: {
        datasets: [
          {
            label: 'My First dataset',
            tree: Utils.numbers(NUMBER_CFG),
            datalabels: {
              display: 'auto',
              anchor: 'start',
              align: 45,
              formatter: (value) => Math.trunc(value.v),
              color: 'white',
              font: {
                size: 20
              }
            }
          }
        ],
      },
      options: {
        plugins: {
          datalabels: {
            display: true,
          }
        }
      }
    };
  6. Integrate chartjs-chart-treemap using Script Tags

    main

    To use the treemap plugin in a plain HTML environment without a module bundler, load the Chart.js library first, followed by the chartjs-chart-treemap plugin via their respective minified script files. Once loaded, you can initialize a chart by setting the type to 'treemap' in the Chart constructor.

    <script src="path/to/chartjs/dist/chart.min.js"></script>
    <script src="path/to/chartjs-chart-treemap/dist/chartjs-chart-treemap.min.js"></script>
    <script>
        let myChart = new Chart(ctx, {type: 'treemap', ...});
    </script>
  7. Group treemap data using the groups option

    main

    You can create a hierarchical treemap by providing an array of keys to the groups option within a dataset. Each string in the array represents a level of nesting in the hierarchy. For example, groups: ['region', 'division'] will first group data by region, and then sub-group those regions by division.

    When using groups, the tree property should contain the hierarchical data structure, and the key property specifies which numeric value determines the size of the rectangles at each level.

    const config = {
      type: 'treemap',
      data: {
        datasets: [{
          tree: Data.statsByState,
          key: 'area',
          groups: ['region', 'division'],
          spacing: 1,
          borderWidth: 0.5,
          borderColor: 'rgba(200,200,200,1)',
          backgroundColor: 'rgba(220,230,220,0.3)',
          hoverBackgroundColor: 'rgba(220,230,220,0.5)',
        }]
      },
      options: {
        // ...
      }
    };
  8. Install chartjs-chart-treemap via CDN

    main

    To use the module via CDN, include both the Chart.js script and the chartjs-chart-treemap script in your HTML file.

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-chart-treemap"></script>
  9. Configure TypeScript for Treemap Datasets

    main

    Because the treemap controller builds the data array from the tree property at runtime, TypeScript definitions require the data property to be present on every dataset. To satisfy this without providing actual data (which is handled by the controller), provide an empty array to the data property.

    const dataset = {
      data: [],
      tree: [15, 6, 6, 5, 4, 3, 2, 2],
    };
  10. Integrate chartjs-chart-treemap with Bundlers (Webpack, Rollup, etc.)

    main

    When using modern module bundlers, import the necessary components from both chart.js and chartjs-chart-treemap. You must register the TreemapController and TreemapElement along with the standard Chart.js registerables to enable the treemap functionality.

    import {Chart, registerables} from 'chart.js';
    import {TreemapController, TreemapElement} from 'chartjs-chart-treemap';
    
    Chart.register(...registerables, TreemapController, TreemapElement);