Многострочный график будет иметь три важных массива объектов, которые необходимо создать, назначенные:
chart.data.labels
- для маркировки по оси X (например, независимая переменная, такая как время) chart.data.datasets
- для маркировки по оси Y (включая несколько строк) chart.options.scales.yAxes
- для свойств линии
Если выиметь уже существующий набор данных (в данном конкретном случае objectArray
), который содержит уже существующие данные, связанные с конкретными именами строк, вы можете создать постоянный массив, содержащий строки с одинаковыми именами (в данном случае NAME_ARRAY
), а также временные массивы для каждого набора данных (name1 = []; name2 = [];
и т. д.), полученные путем итерации цикла for.
Это можно увидеть с помощью:
// '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
}
}
});
}
}