使用 chartjs-chart-geo 插件和 react-chartjs-2 实现分区统计图



我正在尝试创建一个美国分区统计图,其功能类似于 - 如果与 chartjs-chart-geo 中使用 chartjs-2 包装器使用chartjs 的 react-chartjs-2包装器的示例不同。

我遇到的问题是如何将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 的示例。我将 canvas 元素与 useEffect 一起使用。最初加载页面时,画布尚未准备就绪,因此我们必须检查画布是否存在,然后才能创建图表。

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>
)
}

最新更新