如何使用 Chart.js 指定“每个数据集”解析?

Ann*_*nne 5 javascript chart.js

我试图弄清楚在指定数据集时如何使用ChartJS 中的选项,但在从文档中重现此示例时yAxisKey遇到了麻烦。我尝试搜索涉及( 或)、选项以及有关指定 的一般信息的问题,但不幸的是到目前为止还是空白。yAxisKeyxAxisKeyparsingdatasets

例子

<!doctype html>
<html>
<head>
    <title>Example Chart</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        const data = [{x: 'Jan', net: 100, cogs: 50, gm: 50}, {x: 'Feb', net: 120, cogs: 55, gm: 75}];
        const config = {
                type: 'bar',
                data: {
                    labels: ['Jan', 'Feb'],
                    datasets: [{
                        label: 'Net sales',
                        data: data,
                        parsing: {
                            yAxisKey: 'net'
                        }
                    }, {
                        label: 'Cost of goods sold',
                        data: data,
                        parsing: {
                            yAxisKey: 'cogs'
                        }
                    }, {
                        label: 'Gross margin',
                        data: data,
                        parsing: {
                            yAxisKey: 'gm'
                        }
                    }]
                },
            };

        window.onload = function() {
            const ctx = document.getElementById('canvas').getContext('2d');
            let chart  = new Chart(ctx, config);
        };
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

这为我生成了一个看起来空洞的图表。

空图表结果的屏幕截图

我错过了一些明显的东西吗?误解了语法?

提前致谢!

umi*_*der 8

parsing由于您当前使用的 Chart.js 版本 2.8.0 中尚不提供按数据集选项,因此您仍然可以通过该Array.map()函数获得相同的结果。

请查看您修改后的代码,看看它是如何工作的。

<!doctype html>
<html>

<head>
  <title>Example Chart</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
</head>

<body>
  <canvas id="canvas"></canvas>
  <script>
    const data = [
      { x: 'Jan', net: 100, cogs: 50, gm: 50 }, 
      { x: 'Feb', net: 120, cogs: 55, gm: 75 }
    ];
    const config = {
      type: 'bar',
      data: {
        labels: data.map(o => o.x),
        datasets: [{
          label: 'Net sales',
          data: data.map(o => o.net)
        }, {
          label: 'Cost of goods sold',
          data: data.map(o => o.cogs)
        }, {
          label: 'Gross margin',
          data: data.map(o => o.gm)
        }]
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    };

    window.onload = function() {
      const ctx = document.getElementById('canvas').getContext('2d');
      let chart = new Chart(ctx, config);
    };
  </script>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)