使用 chart.js 的具有不同数据的多个图表

Multiple charts with different data using chart.js

我在 HTML 页面上有 3 个图表,我使用 class 而不是 id 以避免重复代码, 我需要帮助来更改其中一个的数据,我尝试了几种方法但问题仍然存在, 这是代码

const charts = document.getElementsByClassName('doughnut-chart')
for (chart of charts) {
  const ctx = chart.getContext('2d');
  const config = {
    type: 'doughnut',
    data: {
      datasets: [{
        data: [50, 60, 20, 33],
        backgroundColor: ["#1CCFEC", "#A9EDF8", "#BDECDC", "#00D295"],
        label: 'Energy usage'
      }],
      labels: ["VISA", "AMEX", "MC", "DEBIT"]
    },
    options: {
      responsive: true,
      cutoutPercentage: 85,
      legend: {
        display: false
      },
      legendCallback: function (chart) {
        // Return the HTML string here.
        console.log(chart.data.datasets);
        const text = [];
        text.push(`<ul class="${chart.id}-legend flex-center-vh flex-space-evenly">`);
        for (let i = 0; i < chart.data.datasets[0].data.length; i++) {
          text.push(`<li class="flex-center-vh"><span class="item-bg" id="legend-${i}-item" style="background-color:${chart.data.datasets[0].backgroundColor[i]}">`);
          text.push(`</span>`);
          if (chart.data.labels[i]) {
            text.push(`<span class="legent-item text-gray fw600 fs10">${chart.data.labels[i]}</span>`);
          }
          text.push(`</li>`);
        }
        text.push(`</ul>`);
        return text.join("");
      },
    }
  };
    const legendContainer = document.querySelectorAll('.doughnut-legend')
  legendContainer.forEach(function (thisLegend) {
    thisLegend.innerHTML = window.chartInstance.generateLegend();
  })
  var chartInstance = new Chart(ctx, config);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script>
<div class="chart-container">
                <canvas id="chart1" class="doughnut-chart"></canvas>   
                <div class="doughnut-legend"></div>            
              </div>
              <div class="chart-container">
                <canvas id="chart2" class="doughnut-chart"></canvas>  
                <div class="doughnut-legend"></div>         
              </div>
              <div class="chart-container">
                <canvas id="chart3" class="doughnut-chart"></canvas>  
                <div class="doughnut-legend"></div>         
              </div>

未设置 window.chartInstance 而且,我对逻辑的理解是期望三个不同的实例以便为每个实例调用 generateLegend()

UPDATED 展示如何更改其中一个图表的数据: 将 legendContainer 移出 charts 循环;现在使用 K Scandrett 建议的图表实例数组。

这是一个提案(节选)。注意主循环内图表的实例化和主循环外图例的生成。

let allCharts = [];

const charts = document.getElementsByClassName("doughnut-chart");
for (chart of charts) {
  const ctx = chart.getContext("2d");
  const config = {
    // ...
  };

  var chartInstance = new Chart(ctx, config);
  allCharts.push(chartInstance);
}

let legendContainer = document.querySelectorAll(".doughnut-legend");
legendContainer.forEach(function (thisLegend, i) {
  thisLegend.innerHTML = allCharts[i].generateLegend();
});

// update data
const chartToModify = allCharts[1]
chartToModify.data.datasets[0].data.pop();
chartToModify.data.datasets[0].data.pop();
chartToModify.data.labels.pop();
chartToModify.data.labels.pop();
chartToModify.update();

// update legends
legendContainer = document.querySelectorAll(".doughnut-legend");
legendContainer.forEach(function (thisLegend, i) {
  thisLegend.innerHTML = allCharts[i].generateLegend();
});

更改其中一张图表的数据记录在 https://www.chartjs.org/docs/3.3.2/developers/updates.html。请注意 update().

的电话

完整代码在这里https://codepen.io/beezital/pen/yLzRqXz