User7723337
User7723337

Reputation: 12018

Chart.js issue in plotting numeric X and Y in line chart

I have bellow Code to display a Chart using Chart.js.

<canvas id="canvasline" width="200" height="200"></canvas>

<script>
var ctx = document.getElementById('canvasline').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['0', '30', '50'],
    datasets: [{
      data: [
        { x: "0", y: 0 },
        { x: "10", y: 10 },
        { x: "20", y: 20 },
        { x: "30", y: 30 },
        { x: "40", y: 40 },
        { x: "50", y: 50 },
      ],
      borderWidth: 1
    }]
  },
  options: {
      legend: {
        display: false
      },
      scales: {
      yAxes: [{
        ticks: {
          display: true,
          suggestedMin: 0,
          suggestedMax: 100,
          maxTicksLimit: 10
        },        
        gridLines: {
          display: true
        }
      }],
      xAxes: [{
        ticks: {
          display: true,
          suggestedMin: 0,
          suggestedMax: 100,
          maxTicksLimit: 3
        },        
        gridLines: {
          display: true
        }
      }]
    }
  }
});
</script>

Working Code Example:
https://jsfiddle.net/2vcrsq6n/

I am facing the below issues:

  1. For the X-Axis label "30", I see X data "10" is getting displayed
  2. At the runtime I get an JSON array with X and Y values as an array, I want to plot this X and Y numbers on the graph how should I implement it.

Upvotes: 0

Views: 1085

Answers (1)

uminder
uminder

Reputation: 26150

When the data is specified as individual points through objects that contain an x and an y property, you should not define data.labels.

Also make sure, the x and y values are numbers but not strings.

Please take a look at your amended code below that uses the most recent stable version of Chart.js (2.9.3).

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'scatter',
  data: {
    datasets: [{
      data: [
        { x: 0, y: 0 },
        { x: 10, y: 10 },
        { x: 20, y: 20 },
        { x: 30, y: 30 },
        { x: 40, y: 40 },
        { x: 50, y: 50 }
      ],
      showLine: true,
      fill: false,
      borderWidth: 1
    }]
  },
  options: {
      legend: {
        display: false
      },
      scales: {
      yAxes: [{
        ticks: {
          suggestedMin: 0,
          suggestedMax: 100,
          maxTicksLimit: 10
        }
      }],
      xAxes: [{
        ticks: {
          suggestedMin: 0,
          suggestedMax: 100,
          maxTicksLimit: 3
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart"></canvas>

To update your chart with new data, simply add or replace the data in the dataset and invoke chart.update() afterwards.

myChart.data.datasets[0].data = <new data>;
myChart.update();

Upvotes: 1

Related Questions