-
Notifications
You must be signed in to change notification settings - Fork 0
/
chart.js
116 lines (109 loc) · 3.52 KB
/
chart.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Utility function to generate a color based on an index
function getColor(index) {
const colors = [
'#4e79a7', '#f28e2c', '#e15759', '#76b7b2', '#59a14f',
'#edc949', '#af7aa1', '#ff9da7', '#9c755f', '#bab0ab'
];
return colors[index % colors.length];
}
// Function to initialize a new chart
function initChart(metricName, datasets, startDate, endDate) {
const ctx = document.getElementById(`${metricName}Chart`).getContext('2d');
return new Chart(ctx, {
type: 'line',
data: { datasets },
options: {
scales: {
x: {
type: 'time',
time: { unit: 'minute' },
title: {
display: true,
text: 'Time'
},
min: startDate,
max: endDate,
ticks: {
autoSkip: true,
maxTicksLimit: 20
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Value'
},
ticks: {
autoSkip: true,
maxTicksLimit: 10
}
}
},
plugins: {
title: {
display: true,
text: `${metricName} Metrics Over Time`
},
legend: {
position: 'top',
labels: {
usePointStyle: true,
pointStyle: 'circle'
}
},
tooltip: {
mode: 'index',
intersect: false
}
},
responsive: true,
maintainAspectRatio: false,
interaction: {
mode: 'nearest',
axis: 'x',
intersect: false
},
elements: {
line: {
tension: 0.1 // Slight curve on lines
},
point: {
radius: 0 // Hide points
}
}
}
});
}
// Function to update an existing chart or create a new one
function updateChart(existingChart, metricName, datasets, startDate, endDate) {
if (existingChart) {
existingChart.destroy();
}
return initChart(metricName, datasets, startDate, endDate);
}
// Function to add new data points to an existing chart
function addDataToChart(chart, newData) {
newData.forEach(point => {
const timestamp = new Date(point.timestamp * 1000);
chart.data.datasets.forEach((dataset, index) => {
const value = point[dataset.label];
dataset.data.push({ x: timestamp, y: value });
});
});
// Remove old data points if there are too many
const maxDataPoints = 100;
if (chart.data.datasets[0].data.length > maxDataPoints) {
chart.data.datasets.forEach(dataset => {
dataset.data.splice(0, dataset.data.length - maxDataPoints);
});
}
chart.update();
}
// Function to update the time range of a chart
function updateChartTimeRange(chart, startDate, endDate) {
chart.options.scales.x.min = startDate;
chart.options.scales.x.max = endDate;
chart.update();
}
export { initChart, updateChart, addDataToChart, updateChartTimeRange };