Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ChartJS v4 – Using Points in a line chart will result in all x-values at 0

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading