繁体   English   中英

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

[英]Dynamically create dataset objects for multi-line graphing, using pre-defined dataset object arrays (JavaScript / Chart.js)

如何修改此代码,以便为已存在的每个y值数据数组动态创建'datasets'数组内的数据集对象? 这是在与向数组添加数据的函数相同的功能块中执行的(其中两个都在export class AppComponent implements OnInit { ngOnInit() { } }内部export class AppComponent implements OnInit { ngOnInit() { } } ),此前在此处回答: httpsexport class AppComponent implements OnInit { ngOnInit() { } } 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. 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
               }
            }
        });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM