Chart.js线图图例产生错误:未捕获的TypeError:无法读取未定义的属性'0'

问题描述 投票:0回答:1

我正在使用Chart.js库制作折线图,我有一个包含多个数据集的图形,该图形在图形上生成多条线。我希望顶部有一个图例,以显示每个数据集的颜色和标签。

我看了看文档上的示例,并说要添加

legend: {
   display: true
}

到选项。当我尝试此操作时,我的图形不再呈现,并且出现错误:

Uncaught TypeError: Cannot read property '0' of undefined

这里是带有图例选项的代码:

    function renderChart(data, labels){
        var ctx = document.getElementById('myChart').getContext('2d');
        var dsets = [];
        var keys = Object.keys(data);
        console.log(data);
        for (i=0; i<keys.length; i++){
            dset = {
                label: keys[i],
                data: data[keys[i]],
                borderColor: '#'+(Math.random()*0xFFFFFF<<0).toString(16),
                borderCapStyle: 'butt',
            }
            dsets.push(dset);
        }
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: dsets
            },
            options: {
              legend: {display : true},
                scales: {
                    yAxes: [{
                        stacked: false,
                        scaleLabel: {
                            display: true,
                            labelString: 'Minutes'
                        },
                        ticks: {
                            beginAtZero: true
                        }
                    }],
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                            display: false,
                            labelString: 'Months'
                        }
                    }]
                }
            },
        });
    }

这是完整的错误:

Uncaught TypeError: Cannot read property '0' of undefined
    at ChartElement.draw (Chart.js:6178)
    at Chart.Controller.<anonymous> (Chart.js:3964)
    at Object.helpers.each (Chart.js:4545)
    at Chart.Controller.draw (Chart.js:3963)
    at ChartElement.animation.render (Chart.js:3939)
    at Object.startDigest (Chart.js:3625)
    at Chart.js:3599 

有什么想法吗?

javascript chart.js
1个回答
0
投票

您是否也尝试过添加

labels: {
    fontColor: 'rgb(255, 99, 132)'
}

就像文档说https://www.chartjs.org/docs/latest/configuration/legend.html#example吗?

var chart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        legend: {
            display: true,
            labels: {
                fontColor: 'rgb(255, 99, 132)'
            }
        }
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.