chartjs-chart-geo

repository·main·Indexed 18 days ago

https://github.com/sgratzl/chartjs-chart-geo

A Chart.js plugin for geographic data visualization, providing support for Choropleth maps and Bubble Maps (Proportional Symbol maps). It includes a projection scale compatible with d3-geo and utilities like ChartGeo.topojson for converting TopoJSON data into features. The library supports manual registration of controllers and scales for ESM environments and provides specialized classes such as ChoroplethChart and BubbleMapChart.

Tokens
8.4K
Snippets
30
Records
38
Agent score
64%

What's inside chartjs-chart-geo

  1. Explore related Chart.js plugins

    main

    The following plugins are part of the same ecosystem and provide additional specialized chart types and functionalities for Chart.js:

    • chartjs-chart-boxplot: Boxplots and violin charts.
    • chartjs-chart-error-bars: Error bars for bar and line charts.
    • chartjs-chart-funnel: Funnel charts.
    • chartjs-chart-geo: Map, bubble maps, and choropleth charts (this project).
    • chartjs-chart-graph: Graphs, trees, and networks.
    • chartjs-chart-pcp: Parallel coordinate plots.
    • chartjs-chart-venn: Venn and Euler diagrams.
    • chartjs-chart-wordcloud: Word clouds.
    • chartjs-plugin-hierarchical: Hierarchical categorical axes that support expanding and collapsing.
  2. How Bubble Map charts work

    main

    A Bubble Map (type: bubbleMap), also known as a Proportional Symbol map, renders dots on a map where the size of the dot is scaled according to a numerical value.

    Data Structure

    Unlike standard bubble charts that use x, y, and r, a Bubble Map uses:

    • longitude: The longitude coordinate.
    • latitude: The latitude coordinate.
    • value: The numerical value used by the sizeScale to determine the pixel radius.

    Styling

    Bubble Maps use the standard Chart.js Point Element styling options. They also support outline* and graticule* options.

    Legend

    A sizeScale is used to map values to symbol radius size, similar to how Choropleth charts use a color scale.

    interface IBubbleMapPoint {
      longitude: number;
      latitude: number;
      value: number;
    }
  3. How Choropleth charts work

    main

    A Choropleth chart (type: choropleth) renders maps where areas are filled based on numerical values.

    Data Structure

    Each data point in the datasets[].data array must contain:

    • .feature: The TopoJSON feature object to render.
    • .value: The numerical value used for coloring.

    To process TopoJSON files, use the ChartGeo.topojson utility (exposed in the global context) to convert raw TopoJSON data into features.

    Configuration Example

    const us = await fetch('https://cdn.jsdelivr.net/npm/us-atlas/states-10m.json').then((r) => r.json());
    
    // Extract features using ChartGeo.topojson
    const nation = ChartGeo.topojson.feature(us, us.objects.nation).features[0];
    const states = ChartGeo.topojson.feature(us, us.objects.states).features;
    
    const alaska = states.find((d) => d.properties.name === 'Alaska');
    const california = states.find((d) => d.properties.name === 'California');
    
    const config = {
      type: 'choropleth',
      data: {
        labels: ['Alaska', 'California'],
        datasets: [{
          label: 'States',
          outline: nation, // Optional: outline to compute bounds
          showOutline: true,
          data: [
            { value: 0.4, feature: alaska },
            { value: 0.3, feature: california }
          ]
        }]
      },
      options: {
        scales: {
          projection: {
            projection: 'albersUsa' // Use D3 projection names without the 'geo' prefix
          }
        }
      }
    };
    const us = await fetch('https://cdn.jsdelivr.net/npm/us-atlas/states-10m.json').then((r) => r.json());
    
    // whole US for the outline
    const nation = ChartGeo.topojson.feature(us, us.objects.nation).features[0];
    // individual states
    const states = ChartGeo.topojson.feature(us, us.objects.states).features;
    
    const alaska = states.find((d) => d.properties.name === 'Alaska');
    const california = states.find((d) => d.properties.name === 'California');
    
    const config = {
      data: {
        labels: ['Alaska', 'California'],
        datasets: [{
          label: 'States',
          outline: nation, // ... outline to compute bounds
          showOutline: true,
          data: [
            {
              value: 0.4,
              feature: alaska // ... the feature to render
            },
            {
              value: 0.3,
              feature: california
            }
          ]
        }]
      },
      options: {
        scales: {
          projection: {
            projection: 'albersUsa' // ... projection method
          }
        }
      }
    };
  4. Register chartjs-chart-geo in ESM environments

    main

    Because the ESM build supports tree shaking and has no side effects, Chart.js will not automatically register the new controllers or scales. You must manually register them.

    Option A: Manual Registration

    Use Chart.register to include the necessary components:

    import { Chart } from 'chart.js';
    import { ChoroplethController, GeoFeature, ColorScale, ProjectionScale } from 'chartjs-chart-geo';
    
    Chart.register(ChoroplethController, GeoFeature, ColorScale, ProjectionScale);
    
    const chart = new Chart(ctx, {
      type: 'choropleth',
      data: { /* ... */ }
    });

    Option B: Using Wrapper Classes

    Import the specialized chart class directly:

    import { ChoroplethChart } from 'chartjs-chart-geo';
    
    const chart = new ChoroplethChart(ctx, {
      data: { /* ... */ }
    });
    import { Chart } from 'chart.js';
    import { ChoroplethController, GeoFeature, ColorScale, ProjectionScale } from 'chartjs-chart-geo';
    
    // register controller in chart.js and ensure the defaults are set
    Chart.register(ChoroplethController, GeoFeature, ColorScale, ProjectionScale);
    
    const chart = new Chart(document.getElementById('canvas').getContext('2d'), {
      type: 'choropleth',
      data: {
        // ...
      },
    });
  5. Install chartjs-chart-geo

    main

    To use geographic charts in your Chart.js project, install both chart.js and chartjs-chart-geo via npm.

    npm install --save chart.js chartjs-chart-geo
  6. Control size mapping mode: 'area' vs 'radius'

    main

    When configuring a SizeScale, you can choose how the data value maps to the point's radius using the mode option:

    • area (default): The area of the circle increases linearly with the data value. This is recommended for better visual comparison of magnitudes, as it prevents large values from appearing disproportionately massive compared to small ones.
    • radius: The radius of the circle increases linearly with the data value.

    Example configuration:

    {
      "mode": "area"
    }
  7. Configure a Choropleth map

    main

    Choropleth charts are configured using three main components:

    1. Dataset Options: Controlled via IChoroplethControllerDatasetOptions.
    2. Projection: The projection scale defines how geometric features are projected into pixel space. See IProjectionScaleOptions for available options.
    3. Color Scale: The color scale handles the conversion from a data value to a specific color. See IColorScaleOptions for available options.
  8. Configure a Bubble Map

    main

    Bubble maps are configured using three main components:

    1. Dataset Options: Controlled via IBubbleMapControllerDatasetOptions.
    2. Projection: The projection scale defines how geometric features are projected into pixel space. See IProjectionScaleOptions for available options.
    3. Size Scale: The size scale handles the conversion from a data value to a circle's radius or area. See ISizeScaleOptions for available options.
  9. How LegendScale and LogarithmicLegendScale work

    main

    LegendScale and LogarithmicLegendScale are specialized Chart.js scales designed to render a visual color legend (a color bar) alongside the scale.

    • LegendScale: A linear scale that includes legend rendering logic. It uses the property option to extract values from data elements.
    • LogarithmicLegendScale: A logarithmic version of the legend scale. It uses Math.log10 to normalize values for the scale and legend.

    Both scales use the align option to determine if the legend is horizontal (top or bottom) or vertical (left or right). This alignment dictates how length and width are applied and how the indicator is drawn.

  10. Create a Bubble Map in Area Mode

    main

    To create a Bubble Map where bubbles represent areas (often used to visualize data proportional to geographic size), you need to provide a data object containing geographic features and bubble coordinates, along with a config object that specifies the chart type as a bubble map.

    In this mode, the chart typically uses the bubbleMap chart type. The data structure requires a datasets array where each dataset contains data points. Each point in the data array should correspond to a geographic feature or coordinate and include a value that determines the bubble's size.

    // Note: This example relies on external config and data files
    // defined in the repository structure.
    
    import { config } from './area';
    
    // The configuration includes the chart type and options
    // The data includes the geographic features and bubble values
    new Chart(ctx, {
      type: 'bubbleMap',
      data: config.data,
      options: config.options
    });
  11. Implement a Custom Tooltip Center in Choropleth Charts

    main

    This example demonstrates how to configure a ChoroplethChart component to use a custom tooltip center. The implementation relies on a configuration object (config.options) and a dataset (config.data) defined in an external TypeScript file. In a Vue-based environment, you can render this by importing the configuration and passing it to the <ChoroplethChart /> component.

    <script setup>
    import {config} from './center';
    </script>
    
    <ChoroplethChart
      :options="config.options"
      :data="config.data"
    />
  12. Create a Bubble Map

    main

    A Bubble Map visualizes data points using circles (bubbles) placed at specific geographic coordinates. The size and color of the bubbles typically represent different data dimensions. In chartjs-chart-geo, this is implemented using the BubbleMapChart component. You must provide a data object containing the bubble coordinates and values, and an options object for styling.

    // Example usage pattern for a Bubble Map
    <BubbleMapChart
      :options="bubble.options"
      :data="bubble.data"
    />