2👍
✅
First you need to define a unique xAxis
and define it as a time cartesian axis.
xAxes: [{
type: 'time',
time: {
unit: 'minute',
tooltipFormat: 'HH:mm:ss'
}
}],
Then you define a linear cartesian yAxis
for each dataset
and make sure, the value of the yAxis.id
matches the corresponding dataset.yAxisID
. Use ‘yAxis.position’ to define whether the axis shall appear left
or right
of the chart.
Optionally you may also define the following Plugin Core API beforeLayout
function that makes sure that an yAxis
is also hidden when it’s data set is hidden through a mouse click on a legend label.
plugins: [{
beforeLayout: chart => chart.data.datasets.forEach((ds, i) => chart.config.options.scales.yAxes[i].display = !ds._meta[0].hidden)
}],
Please have a look at below runnable code snippet that illustrates how it can be done.
const now = new Date().getTime();
const timestamps = new Array(10).fill().map((v, i) => now - i * 60000).reverse();
new Chart('chart', {
type: 'line',
plugins: [{
beforeLayout: chart => chart.data.datasets.forEach((ds, i) => chart.config.options.scales.yAxes[i].display = !ds._meta[0].hidden)
}],
data: {
labels: timestamps,
datasets: [{
label: 'CPU',
yAxisID: 'yAxis-CPU',
data: [68, 70, 71, 72, 75, 75, 76, 77, 79, 76],
borderColor: 'red',
fill: false
},
{
label: 'RAM',
yAxisID: 'yAxis-RAM',
data: [22, 23, 23, 23, 22, 20, 22, 22, 23, 25],
borderColor: 'blue',
fill: false
},
{
label: 'IO-RATE',
yAxisID: 'yAxis-IO-RATE',
data: [0.5, 0.6, 0.7, 0.8, 0.8, 0.2, 0.1, 0.1, 0.2, 0.2],
borderColor: 'green',
fill: false
}
]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'minute',
displayFormats: {
minute: 'HH:mm'
},
tooltipFormat: 'HH:mm:ss'
}
}],
yAxes: [{
id: 'yAxis-CPU',
type: 'linear',
position: 'left',
scaleLabel: {
display: true,
labelString: 'CPU %'
},
gridLines : {
display: false
},
ticks: {
beginAtZero: true
}
},
{
id: 'yAxis-RAM',
type: 'linear',
position: 'left',
scaleLabel: {
display: true,
labelString: 'RAM %'
},
gridLines : {
display: false
},
ticks: {
beginAtZero: true
}
},
{
id: 'yAxis-IO-RATE',
type: 'linear',
position: 'right',
scaleLabel: {
display: true,
labelString: 'IO-Rate %'
},
gridLines : {
display: false
},
ticks: {
beginAtZero: true
}
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="chart" height="90"></canvas>
Source:stackexchange.com