chart js line chart with iso date [duplicate]
I'm trying to show only the month and year in the x-axis of my chart by using momentjs, but it is only putting what appears to be the full moment date in the x-axis.
I have been looking at many examples of people doing this but none of them seem to work in the latest version of chartjs. I am aware of an "adapter" needed for use with momentjs which I have included but have no way to know if it is working.
Here is a jsfiddle of the code I am using, help would be greatly appreciated. https://jsfiddle.net/7z20jg68/
I also have error telling me Invalid scale configuration for scale: x
which is confusing because my x axis seems to be in the correct order..Thanks!
Solution 1:
Your X axis scale was indeed invalid, you declared it as an array which is V2 syntax, in V3 all the scales are their own object where the key of the object is the scaleID. So removing the array brackets around the x axis scale object will resolve the issue.
Also your legend and tooltip config where wrong and in the wrong place, also V2 syntax.
For all changes please read the migration guide
const gainedChart = document.getElementById('gained-chart').getContext('2d');
const gain = [74.699997, 76.580002, 81.349998, 83.000000, 85.879997, 83.120003, 77.989998, 81.279999];
const dates = ["Jan 2, 20", "Feb 3, 20", "Mar 4, 20", "Apr 5, 20", "May 6, 20", "Jun 9, 20", "Nov 10, 20", "Dec 11, 20"];
let gainData = {
datasets: [{
label: "Gain (%)",
data: gain,
borderColor: 'rgba(255, 66, 66, 1)',
backgroundColor: 'rgba(255, 66, 66, 1)',
pointRadius: 1.2,
pointBackgroundColor: 'rgba(255, 66, 66, 0.8)',
pointHoverRadius: 6,
pointHitRadius: 20,
pointBorderWidth: 2,
}]
};
let gainConfig = {
plugins: {
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
color: 'black'
},
},
tooltip: {
callbacks: {
label: function(tooltipItem, data) {
return parseInt(tooltipItem.parsed.y)
}
}
},
},
scales: {
x: {
type: 'time',
time: {
minUnit: 'month'
}
},
y: {
suggestedMax: 45,
ticks: {
stepSize: 5,
//max: 100
},
},
},
maintainAspectRatio: false,
responsive: true,
};
let lineGainChart = new Chart(gainedChart, {
type: 'line',
data: gainData,
options: gainConfig,
plugins: [{
beforeInit: function(lineGainChart) {
for (let c = 0; c < dates.length; c++) {
let myMoment = moment(dates[c], 'MMM D, YYYY');
lineGainChart.data.labels.push(myMoment);
}
}
}]
});
<canvas class="graph-canvas" id="gained-chart" width="400" height="400"></canvas>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/moment.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>