我正在尝试向使用chart.js创建的图表中添加一些数据。
我得到“未定义”错误。如何向其中添加数据?看起来像是一个愚蠢的傻新手错误...请多多包涵并帮助我。谢谢
var birdsCanvas = document.getElementById("birdsChart");
Chart.defaults.global.defaultFontFamily = "Lato";
Chart.defaults.global.defaultFontSize = 18;
var birdsData = {
labels: ["Spring", "Summer", "Fall", "Winter"],
datasets: [{
//data: [1200, 1700, 800, 200],
data: [5, 10, 3, 9],
backgroundColor: [
"rgba(255, 0, 0, 0.6)",
"rgba(0, 255,200, 0.6)",
"rgba(200, 0, 200, 0.6)",
"rgba(0, 255, 0, 0.6)"
],
borderColor: "rgba(0, 0, 0, 0.8)"
}]
};
var chartOptions = {
startAngle: -Math.PI / 4,
legend: {
position: 'left'
},
animation: {
animateRotate: false
}
};
var polarAreaChart = new Chart(birdsCanvas, {
type: 'polarArea',
data: birdsData,
options: chartOptions
});
//alert ('checking value... birdsData label 1 ' + birdsData.labels[1]);
polarAreaChart.birdsData.datasets.push({
label: 'label2',
backgroundColor: 'rgba(255, 0, 0, 0.6)',
borderColor: 'rgba(255, 0, 0, 0.6)',
data: [9]
});
barChart.update();
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="birdsChart" width="600" height="550"></canvas>
我收到TypeError:PolarAreaChart.birdsData未定义..我只想在用户单击某些内容时通过函数动态添加数据。
谢谢
答案 0 :(得分:0)
您可能想使用polarAreaChart.data.datasets.push({
而不是birdsData
,因为图表对象中没有bridsData
对象:
var birdsCanvas = document.getElementById("birdsChart");
Chart.defaults.global.defaultFontFamily = "Lato";
Chart.defaults.global.defaultFontSize = 18;
var birdsData = {
labels: ["Spring", "Summer", "Fall", "Winter"],
datasets: [{
//data: [1200, 1700, 800, 200],
data: [5, 10, 3, 9],
backgroundColor: [
"rgba(255, 0, 0, 0.6)",
"rgba(0, 255,200, 0.6)",
"rgba(200, 0, 200, 0.6)",
"rgba(0, 255, 0, 0.6)"
],
borderColor: "rgba(0, 0, 0, 0.8)"
}]
};
var chartOptions = {
startAngle: -Math.PI / 4,
legend: {
position: 'left'
},
animation: {
animateRotate: false
}
};
var polarAreaChart = new Chart(birdsCanvas, {
type: 'polarArea',
data: birdsData,
options: chartOptions
});
//alert ('checking value... birdsData label 1 ' + birdsData.labels[1]);
polarAreaChart.data.datasets.push({
label: 'label2',
backgroundColor: 'rgba(255, 0, 0, 0.6)',
borderColor: 'rgba(255, 0, 0, 0.6)',
data: [9]
});
polarAreaChart.update();
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="birdsChart" width="400" height="400"></canvas>