I am facing a rather strange problem with line charts and ChartJS. Given the following very simple code. I expect to have a line chart where 3 data points (at x: 0, x:1 and x: 2). But instead, all points are shown at x:0. According to the docs: https://www.chartjs.org/docs/latest/charts/line.html#data-structure it should be possible to use the given notation to draw the line graph.
var data = {
datasets: [
{
label: "Bug Report",
data: [
{ x: 0, y: 1 },
{ x: 1, y: 2 },
{ x: 2, y: 4 }
]
}
]
};
const ctx = document.getElementById("myChart");
new Chart(ctx, {
type: "line",
data: data
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div>
<canvas id="myChart"></canvas>
</div>
The Issue is due to missing configuration for the x-axis. By default, Chart.js
expects data to be indexed by integers starting from 0 unless explicitly set to use the x values from your data objects. A work around is to use the provided snippet below, which is as simple as adding the ff code to your chart.js
file.
options: {
scales: {
x: {
type: 'linear',
position: 'bottom'
}
}
}