使用预定义的数据集对象数组(JavaScript / Chart.js)动态创建用于多线制图的数据集对象

时间:2019-06-21 21:27:40

标签: javascript arrays object dynamic chart.js

我将如何修改此代码,以便为每个现有的y值数据数组在“数据集”数组内动态创建数据集对象?这是在与向数组添加数据的功能相同的功能块中执行的(两个都在export class AppComponent implements OnInit { ngOnInit() { } }内),在此处前面曾回答过:https://stackoverflow.com/a/56710201/5067233(以提供适当的源代码功劳)。 >

我当前的方法显然是硬编码的,既没有效率,也没有动态。

我的通用代码:

one = [];
two = [];
three = [];

...code that adds data to the arrays

    // The actual graph formatting
    this.chart = new Chart('canvas', {
      type: 'line',
      data: {
        labels: this.one,
        datasets: [
          {
            data: this.two,
            label: 'two',
            yAxisID: 'two',
            borderColor: '#3CBA9F',
            fill: false,
          },
          {
            data: this.three,
            label: 'three',
            yAxisID: 'three',
            scaleOverride: true,
            borderColor: '#51b7ed',
            fill: false,
          },
          ...n amount of datasets here
        ]
      },
    });

1 个答案:

答案 0 :(得分:0)

多折线图将需要创建三个重要的对象数组,并将其分配给:

  1. chart.data.labels-用于x轴标记(例如,像时间这样的自变量)
  2. chart.data.datasets-用于y轴标记(包括多行)
  3. chart.options.scales.yAxes-用于行的属性

如果您有一组预先存在的数据(在这种情况下为objectArray),其中包含与特定行名相关联的预先存在的数据,则可以创建一个常量数组,其中包含相同名称的字符串(在这种情况下为NAME_ARRAY),以及通过for循环迭代获得的每个数据集的临时数组(name1 = []; name2 = [];等)。

这可以通过以下方式看到:

// 'N' PRE-DEFINED CONSTANTS

// Names of the lines you are graphing
const NAME_ARRAY = [
  'name1',
  'name2',
  'name3'
];
// Colors of lines in same order as aforementioned names
const HEX_ARRAY = [
  '#3CBA9F',
  '#51b7ed',
  '#FF0000'
];

// GRAPHING LINE PROPERTIES SHARED BY 'N' LINES

// Doesn't require arguments so can utilize .map() effectively
const datasetLineArray = NAME_ARRAY.map((value,index,array) => {
  return {
    id: value,
    display: false,
    ticks: {
      // INSERT YOUR PROPERTIES HERE (although none required)
      // max: 1000,
      // min: 100000,
      // reverse: true,
      // stepSize: 10000,
      // suggestedMax: 500,
      // etc...
    },
  };
});
// Utilizes two arguments so needs object creation upon call rather than pre-defined array mapping (as in .map())
function addDataToDataset(dataArray, index) {
  const tempObject = {
    data: dataArray,
    label: NAME_ARRAY[index],
    yAxisID: NAME_ARRAY[index],
    borderColor: HEX_ARRAY[index],
    fill: false,
    scaleOverride: true,
  };
  return tempObject;
}

// CHART.JS GRAPH CREATION

export class AppComponent implements OnInit {
    // Store dataset objects
    Dataset_Object_Array = [];

    // Store data with same name as incoming objects
    name1 = [];
    name2 = [];
    name3 = [];

    // Essentially main()
    ngOnInit() { 
        for (const categoryArray in objectArray) {
            const categoryObject = objectArray[categoryArray];
            // these names are arbitrary, just note that categoryObject is an object that contains 
            // the property 'category' which is the equivalent of the name from the constant array 
            // 'NAME_ARRAY'; however, this object may contain data that we need to parse

            // IMPORTANT BIT
            this.Dataset_Object_Array.push(addDataToDataset(this[categoryObject.category], categoryArray));
        }

        // The actual graph formatting
        this.chart = new Chart('canvas', {
            type: 'line',
            data: {
                // **IMPORTANT BIT**
                labels: this.one, // x-axis labeling

                // **IMPORTANT BIT**
                datasets: this.Dataset_Object_Array // multi-line y-axis labeling as well as data
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                legend: {
                  display: true
                },
                scales: {
                  xAxes: [{
                    display: true,
                    ticks: {
                        callback: function(value, index, values) {
                          return parseFloat(value).toFixed(3);
                        },
                    }
                 }],

                 // **IMPORTANT BIT**
                 yAxes: datasetLineArray, // property meta-data for the lines
               }
            }
        });
    }
}