Reputation: 121
Using chart.js I would like to reformat my bottom chart labels into MM DD format (ie. Feb 2)
How do I get chart.js to recognize the data as dates and convert it?
It comes in like this from my csv file:
2020-02-06
Here is my chart.js coding but it doesn't seem to work.
data: {
labels: dollar.years,
datasets: [
{label: 'Cdn dollar in cents',
data: dollar.vals,
fill: false,
borderColor: '#4BD0B0',
pointRadius: 0,
borderWidth: 8
}
]
},
options: {
legend:{
display:false,
usePointStyle: true,
labels: {
boxwidth:10,
rotation:90
}
},
scales: {
yAxes: [{
gridLines:{
display:true
},
ticks: {
min: .74,
max: .76,
stepSize: .025,
}
}],
xAxes: [{
gridLines:{
display:true
},
ticks: {
labelOffset: 1,
},
}],
}
}
});
}
Upvotes: 1
Views: 8690
Reputation: 26190
All you need is to define your xAxis
as a time cartesian axis with a 'day' unit.
The default display format of 'day' is 'MMM D' (for instance 'Feb 2').
options: {
...
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
tooltipFormat: 'MMM DD'
}
...
}]
}
...
}
Please have a look at the following runnable code snippet:
new Chart(document.getElementById('myChart'), {
type: 'line',
data: {
labels: ['2020-02-06', '2020-02-07', '2020-02-08', '2020-02-09', '2020-02-10', '2020-02-11', '2020-02-12'],
datasets: [{
label: 'My Dataset',
data: [0.758, 0.756, 0.755, 0.754, 0.753, 0.758, 0.76],
fill: false,
backgroundColor: 'green',
borderColor: 'green'
}]
},
options: {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: .74,
max: .76,
stepSize: .005
}
}],
xAxes: [{
type: 'time',
time: {
unit: 'day',
tooltipFormat: 'MMM DD'
}
}],
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="80"></canvas>
Upvotes: 3