将绘图数学函数从ChartJs 2转换为3

ddrv8njm  于 2022-12-13  发布在  Chart.js
关注(0)|答案(1)|浏览(150)

我有以下JSON图表配置,它在chartjs2上运行良好:

{
    "type": "line",
    "data": {
        "labels": [0, 100],
        "datasets": [{
            "label": "T = const",
            "function": "function(x) { return 2; }",
            "data": [],
            "fill": false,
            "borderColor": "rgb(75, 192, 192)",
            "tension": 0.1
        }]
    },
    "options": {
        "scales": 
        {
            "x": { "title": { "display": true, "text": "[n]" }},
            "y": { "title": { "display": true, "text": "[u]" }}
        }
    },
    "plugins": [{
        "beforeInit": function(chart) {
          // We get the chart data
          var data = chart.config.data;
  
          // For every dataset ...
          for (var i = 0; i < data.datasets.length; i++) {
  
              // For every label ...
              for (var j = 0; j < data.labels.length; j++) {
  
                  // We get the dataset's function and calculate the value
                  var fct = data.datasets[i].function,
                      x = data.labels[j],
                      y = fct(x);
                  // Then we add the value to the dataset data
                  data.datasets[i].data.push(y);
              }
          }
        }
    }]
}

我遇到以下错误:

Error: fct is not a function

如何转换这个例子,使它与ChartJs 3?我猜chart API中的一些东西已经改变,但我不知道到底是什么,以及如何将它应用到我的datasets例子。

wfsdck30

wfsdck301#

我想你自己也可以很容易地解决它,只要去掉引号:

"function": "function(x) { return 2; }",

"function": function(x) { return 2; },

在数据集中

...
 "datasets": [{
     "label": "T = const",
     "function": function(x) { return 2; },
     "data": [],
     "fill": false,
     "borderColor": "rgb(75, 192, 192)",
     "tension": 0.1
}]
...

相关问题