我正在尝试使用**react-chartjs-2chartjs Package 器创建一个美国地区分布图,其功能类似于(如果与chartjs-chart-geo中的this example**不同)。
我遇到的问题是如何将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和**react-simple-maps**。谢谢!
1条答案
按热度按时间eni9jsuy1#
我通过使用以下导入获得了使用React的示例。我使用了带有useEffect的canvas元素。当页面最初加载时Canvas还没有准备好,所以我们必须在创建图表之前检查canvas是否存在。