为什么我的两张图表重复相同的标签

Why are my two charts repeating the same label?

本文关键字:标签 我的 两张 为什么      更新时间:2024-05-26

我必须使用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');

https://jsfiddle.net/4tg2uvc6/

因为它们共享对同一数据对象的引用。当您调用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');