plot y=mx graph in javascript

To plot a graph with a linear equation y=mx+b where m is the slope, we can use a library such as Chart.js which allows to draw various types of charts and graphs.

Step 1: Include Chart.js library in your HTML file.

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
62 chars
2 lines

Step 2: Create a canvas element in your HTML file that will hold the chart.

<canvas id="myChart" width="400" height="400"></canvas>
56 chars
2 lines

Step 3: In your JavaScript file, create a new instance of the Chart object and provide it with the canvas element's ID.

index.tsx
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
        datasets: [{
            label: 'y = mx',
            data: [],
            backgroundColor: '#ffcd56',
            borderColor: '#ffcd56',
            borderWidth: 1,
            fill:false
        }]
    },
    options:{
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                }
            }]
        }
    }
});
578 chars
25 lines

Step 4: Define the linear equation, calculate y values for given x values and add them to the dataset.

index.tsx
var m=2; // slope
for(let x=0; x<10; x++) {
   chart.data.datasets[0].data.push(m*x);
}
88 chars
5 lines

Step 5: Update the chart with new data.

index.tsx
chart.update();
16 chars
2 lines

The complete code snippet would look like this:

<!DOCTYPE html>
<html>
<head>
  <title>Linear Plot</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <canvas id="myChart" width="400" height="400"></canvas>

  <script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
        datasets: [{
          label: 'y = mx',
            data: [],
            backgroundColor: '#ffcd56',
            borderColor: '#ffcd56',
            borderWidth: 1,
            fill:false
        }]
      },
      options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true,
                    }
                }]
            }
      }
    });

    var m = 2;
    for (let x = 0; x < 10; x++) {
      chart.data.datasets[0].data.push(m*x);
    }
    chart.update();
  </script>
</body>
</html>
985 chars
44 lines

This will draw a graph of y=mx with slope=2. You can modify the value of m to change the slope of the line.

related categories

gistlibby LogSnag