将数据从.csv(d3.js)传递到Chart.js,我是否做错了什么?

yshpjwxd  于 2022-11-07  发布在  Chart.js
关注(0)|答案(1)|浏览(158)

所以我可以看到d3.js完成了它的工作,并从.csv中检索数据(在浏览器控制台中可见),但由于某种原因,我不能在图表上传递这些数据,日志中没有错误等等。)

const chartData = 'data/data.csv';
d3.csv(chartData).then(function(datapoints) {
  console.log(datapoints)
  const data1 = [];
  const data2 = [];
  const data3 = [];

  for (var i = 0; i < datapoints.lenght; i++) {
    data1.push(datapoints[i].data1)
    data2.push(datapoints[i].data2)
    data3.push(datapoints[i].data3)

    }

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Data1', 'Data2', 'Data3'],
        datasets: [{
            label: 'Live data (someday)',
            data: [data1, data2,data3],
            backgroundColor: [
                'rgba(0, 0, 255)',

            ],
brqmpdu1

brqmpdu11#

问题是datasets.data最终是一个数组的数组,但是Chart.js需要一个平面的值数组。如果不看数据,很难判断,但是你可能需要定义3个单独的datasets

const chartData = 'data/data.csv';
d3.csv(chartData).then(function(datapoints) {    
  const myChart = new Chart('myChart', {
    type: 'line',
    data: {
        labels: datapoints.map((o, i) => i),
        datasets: [
          {
            label: 'Live data 1 (someday)',
            data: datapoints.map(o => o.data1),
            backgroundColor: 'rgb(0, 0, 255)' 
          },
          {
            label: 'Live data 2 (someday)',
            data: datapoints.map(o => o.data2),
            backgroundColor: 'rgb(0, 255, 0)' 
          },
          {
            label: 'Live data 3 (someday)',
            data: datapoints.map(o => o.data3),
            backgroundColor: 'rgb(255, 0, 0)' 
          }
        ],
        ...

相关问题