chart.js

How to create simple linear chart?


I try to create a simple chart with several lines and common axis. Lines are given by sets of points, points with x and y - integers. Fg Line 1 is [{x: 10, y: 10},{x: 20, y: 15},{x: 30, y: 10},{x: 40, y: 12},{x: 50, y: 10}] and Line 2 is [{x: 10, y: 10},{x: 17, y: 11},{x: 22, y: 28},{x: 35, y: 44},{x: 53, y: 16}]. Values of x are diffrent. I'd like to have one chart with 2 lines. Each line should have Bezier approximation. The range of x axis should be defined, fg from 10 to 53 in the example above.

How to create such a chart in chart.js?


Solution

  • You'll need a scatter plot for non-uniform X coordinates:

    const d1 = [{x: 10, y: 10},{x: 20, y: 15},{x: 30, y: 10},{x: 40, y: 12},{x: 50, y: 10}];
    const d2 = [{x: 10, y: 10},{x: 17, y: 11},{x: 22, y: 28},{x: 35, y: 44},{x: 53, y: 16}];
    const config = {
      type: 'scatter',
      data: {
        datasets: [{data: d1, showLine: true}, {data: d2, showLine: true}],
      },
    };
    
    new Chart(document.getElementById('c'), config);
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
    <canvas id="c"></canvas>