[英]React ChartJS Scatter Plot - cannot plot the data
I am trying to generate a scatterplot using chartJS.我正在尝试使用 chartJS 生成散点图。 The plot wont graph.
plot 不会绘图。 When i feed in data manually by declaring the data, it works fine,
当我通过声明数据手动输入数据时,它工作正常,
var scatter = [
{ x: 65, y: 75 },
{ x: 59, y: 49 },
{ x: 80, y: 90 },
{ x: 81, y: 29 },
{ x: 56, y: 36 },
{ x: 55, y: 25 },
{ x: 40, y: 18 },
]
but when I get the data via an API call and push the data to the array, it won't work.但是当我通过 API 调用获取数据并将数据推送到数组时,它将无法正常工作。 Any suggestions?
有什么建议么? I suspect its to do with how data is pushed onto the array but not sure what's wrong.
我怀疑它与如何将数据推送到阵列上有关,但不确定出了什么问题。
Thank you谢谢
Minimum solution below下面的最小解决方案
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [scatterData, setScatterData] = useState({});
const chart = () => {
var scatter = [];
axios.get('http://dummy.restapiexample.com/api/v1/employees')
.then(res => {
let temp = res.data.data
temp.forEach( i=> {
let age = parseInt(i.employee_age)
let salary = parseInt(i.employee_salary)
scatter.push({"x": age,
"y": salary})
})
}).catch(err => {
console.log(err)
})
console.log(scatter)
setScatterData({
datasets: [
{
label: 'test',
fill: true,
backgroundColor: 'rgba(75,192,192,0.4)',
pointBorderColor: 'rgba(75,192,192,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 10,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 3,
pointHitRadius: 10,
data: scatter,
backgroundColor: [
'rgba(75,192,192,0.6)'
],
borderWidth: 4
}
]
});
}
useEffect(() ={
chart()
},[])
return (
<div className ="container-fluid">
<div class="row">
<div className ="col-md-12">
<Scatter data={scatterData}/>
</div>
</div>
</div>
)
};
Try calling the update method on your chart object/instance after you pushed all the data from the api to your scatter array将所有数据从 api 推送到散点数组后,尝试在图表对象/实例上调用更新方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.