我必须使用ChartJS生成两个条形图。 由于某种原因,顶部和底部图形共享相同的标签?
var data = {
labels: [],
datasets: [
{
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)"
}
]
};
var options = {
animation: true,
responsive: true
};
var ctx1 = document.getElementById("february-chart").getContext("2d");
februaryChart = new Chart(ctx1).Bar(data, options);
var ctx2 = document.getElementById("march-chart").getContext("2d");
marchChart = new Chart(ctx2).Bar(data, options);
februaryChart.addData([2], 'aaaa');
marchChart.addData([5], 'bbbb');
答案 0 :(得分:2)
因为他们正在共享对同一数据对象的引用。当您调用addData方法时,它们都在更改同一个对象。为每个实例提供不同的数据对象,您仍然可以共享选项,假设您希望它们是相同的。
https://jsfiddle.net/onug1tdy/
var marchData = {
labels: [],
datasets: [
{
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)"
}
]
};
var febData = {
labels: [],
datasets: [
{
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)"
}
]
};
var options = {
animation: true,
responsive: true
};
var ctx1 = document.getElementById("february-chart").getContext("2d");
februaryChart = new Chart(ctx1).Bar(febData, options);
var ctx2 = document.getElementById("march-chart").getContext("2d");
marchChart = new Chart(ctx2).Bar(marchData, options);
februaryChart.addData([2], 'aaaa');
marchChart.addData([5], 'bbbb');