We can make creating charts on a web page easy with Chart.js.
In this article, we’ll look at how to create charts with Chart.js.
Time Axis Scale Bounds
We can change the bounds
property to control the scale boundary strategy.
It can either be 'data'
or 'ticks'
.
'data'
makes sure data are fully visible.
'ticks'
makes sure ticks are fully visible.
For example, we can write:
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'First dataset',
data: [{
x: new Date(2020, 1, 1),
y: 1
}, {
t: new Date(2020, 4, 1),
y: 3
}, {
t: new Date(2020, 7, 1),
y: 5
}, {
t: new Date(2020, 10, 1),
y: 7
}]
}],
},
options: {
scales: {
xAxes: [{
type: 'time',
bounds: 'data'
}]
}
}
});
to display the ticks according to the available data so that they’re visible.
Ticks Source
The ticks.source
property controls the tick generation.
The value can be 'auto'
, 'data'
or 'labels'
.
'auto'
generates the optimal ticks based on scale size and time options.
'data'
generates ticks from data.
'labels'
generate ticks from the user given labels only.
For example, we can write:
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'First dataset',
data: [{
x: new Date(2020, 1, 1),
y: 1
}, {
t: new Date(2020, 4, 1),
y: 3
}, {
t: new Date(2020, 7, 1),
y: 5
}, {
t: new Date(2020, 10, 1),
y: 7
}]
}],
},
options: {
scales: {
xAxes: [{
type: 'time',
ticks: {
source: 'auto'
}
}]
}
}
});
to let Chart.js generate the optimal ticks.
Linear Radial Axis
Radial axes are used to specify the radar and polar area chart types.
A linear scale is used to chart numeric data.
Linear interpolation is used to determine where value lies in relation to the center of the axis.
We can change the axis range settings with the ticks.suggestedMin
and ticks.suggestedMax
properties.
For example, we can write:
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'radar',
data: {
datasets: [{
label: 'First dataset',
data: [0, 20, 40, 50]
}],
labels: ['January', 'February', 'March', 'April']
},
options: {
scale: {
ticks: {
suggestedMin: 50,
suggestedMax: 100
}
}
}
});
to change the suggested min and max values.
This way, we can change the scale values to be different from the default.
Radial Axis Step Size
We can also change the step size.
For example, we can write:
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'radar',
data: {
datasets: [{
label: 'First dataset',
data: [0, 20, 40, 50]
}],
labels: ['January', 'February', 'March', 'April']
},
options: {
scale: {
ticks: {
max: 60,
min: 0,
stepSize: 0.5
}
}
}
});
We set the max
and min
values for the axes with those properties.
And stepSize
changes the tick size for the radial axes.
Conclusion
We can change the time axis to what we want.
Also, we can change the radial axis lines.