使用带有 react-chartjs-2 的 chartjs-chart-geo 插件实现等值线图

Implementing a choropleth chart using chartjs-chart-geo plugin with react-chartjs-2

我正在尝试创建一个美国等值线图,其功能类似于 - 如果与 this example from chartjs-chart-geo using react-chartjs-2 chartjs 包装器不同的话。

我 运行 遇到的问题是如何将 chartjs-chart-geo 与 react-chartjs-2 一起使用。我能够使用修改现有图表类型的插件工作,但我不确定如何使用添加新图表类型的插件工作。

到目前为止,这是我的代码:

import React, { useState, useEffect} from "react";
import { Line } from "react-chartjs-2";
import 'chartjs-chart-geo';
import stateUnemployment from "../march-state-unemployment.json"


const JSON_IMPORT = stateUnemployment;

const transformData = obj => {
    let stateNames = [];
    let dataMonth = new Date().getMonth();
    let dataValue = [];

    console.log(obj.length);
    console.log(obj[1].state);
    // Code for parsing json data goes here
    for (let i = 0; i < obj.length; i++) {
        stateNames[i] = obj[i].state;
        dataValue[i] = obj[i].unemploymentPercent;
    }

    return {
        stateNames,
        dataMonth,
        dataValue,
    };
};

const USPageMap = () => {
    const [data, setData] = useState(null);

    useEffect(() => {
        const {dataLabel, dataValue} = transformData(JSON_IMPORT);
        setData({
            labels: dataLabel,
            datasets: [
                {
                    // code for configuring choropleth data goes here?
                    label: "States",
                    data: dataValue,
                }
            ]
        });
    }, []);

    return (
        <div>
            <h2>National Unemployment</h2>
            // Swapping line for Choropleth doesn't seem to work?
            <Line
                data={data}
                options={{
                    maintainAspectRatio: true,
                    legend: {
                        display: false
               },
                plugins: {
                    // setting plugin options usually goes here
                    scale: {
                        projection: 'albersUsa'
                    },
                    geo: {
                        colorScale: {
                            display: true,
                            position: 'bottom',
                            quantize: 5,
                            legend: {
                                position: 'bottom-right',
                            },
                        },
                    },
                }
            }}
        />
        </div>
     );
  };

export default USPageMap;

这里是一个使用 JSON 的例子:

[
  {
    "state": "Alabama",
    "totalUnemployed": "77,988",
    "unemploymentPercent": 3.5
  },
  {
    "state": "Alaska",
    "totalUnemployed": "19,426",
    "unemploymentPercent": 5.6
  },
  {
    "state": "Arizona",
    "totalUnemployed": "196,793",
    "unemploymentPercent": 5.5
  }
]

如果有比 react-chartjs-2 更简单的替代方案,我愿意改变我的方法。我也一直在寻找潜在的替代方案,例如 react-geo-charts and react-simple-maps。谢谢!

我通过使用以下导入获得了使用 React 的示例。我将 canvas 元素与 useEffect 一起使用。 Canvas 在最初加载页面时尚未就绪,因此我们必须在创建图表之前检查 canvas 是否存在。

import { Chart } from 'react-chartjs-2'
import * as ChartGeo from 'chartjs-chart-geo'

    const USPageMap = () =>{
    
        useEffect(()=>{
    
            let canvas = document.getElementById("canvas")
            if(!canvas) return
    
            fetch('https://unpkg.com/us-atlas/states-10m.json').then((r) => r.json()).then((us) => {
    
                const nation = ChartGeo.topojson.feature(us, us.objects.nation).features[0];
                const states = ChartGeo.topojson.feature(us, us.objects.states).features;
              
                const chart = new Chart(canvas.getContext("2d"), {
                  type: 'choropleth',
                  data: {
                    labels: states.map((d) => d.properties.name),
                    datasets: [{
                      label: 'States',
                      outline: nation,
                      data: states.map((d) => ({feature: d, value: Math.random() * 10})),
                    }]
                  },
                  options: {
                    legend: {
                      display: false
                    },
                    scale: {
                      projection: 'albersUsa'
                    },
                    geo: {
                      colorScale: {
                        display: true,
                        position: 'bottom',
                        quantize: 5,
                        legend: {
                          position: 'bottom-right',
                        },
                      },
                    },
                  }
                });
              });
        })
        
        return(
            <div>
                <canvas id='canvas'></canvas>
            </div>
        )
    }