Mark Eggers
Mark Eggers

Reputation: 485

ChartJS scale ticks with scatter plot

I am just starting out with ChartJS. I am exploring the new scatter plot in version 2.6 and would like to start the origin of an X-Y plot at 0:0. I would also like to specify the maximum value of X and Y.

Unfortunately, setting beginAtZero to true and setting a max value for each axis does not seem to work. Sample code below:

    var linedata = {
    type: 'scatter',
    data: {
        datasets: [{
                label: 'Simple Line',
                fill: false,
                data: [
                    {x: 1, y: 2},
                    {x: 2, y: 4},
                    {x: 3, y: 6},
                    {x: 4, y: 8},
                    {x: 5, y: 10},
                    {x: 6, y: 12},
                    {x: 7, y: 14}
                ]
            }
        ]
    }
    };

    var chartOptions = {
        responsive: true,
        maintainAspectRatio: true,
        scales: {
            xAxes: [{
                    ticks: {
                        beginAtZero: true,
                        max: 8
                    },
                    type: 'linear',
                    position: 'bottom'
                }],
            yAxes: [{
                    ticks: {
                        beginAtZero: true,
                        max: 16
                    }
                }]
        }
    };

var lineID = document.getElementById('linechart').getContext('2d');
var lineChart = new Chart(lineID, linedata, chartOptions);

This still ends up with a line (scatter plot) starting at X=1, Y=2, and ending with X=7, Y=14 (rather than 0:0 to 8:16).

Upvotes: 0

Views: 3156

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32879

You are configuring your chart incorrectly. Here is how it should be created ...

var linedata = {
   datasets: [{
      label: 'Simple Line',
      fill: false,
      data: [
         {x: 1, y: 2},
         {x: 2, y: 4},
         {x: 3, y: 6},
         {x: 4, y: 8},
         {x: 5, y: 10},
         {x: 6, y: 12},
         {x: 7, y: 14}
      ]
   }]
};

var chartOptions = {
   responsive: true,
   maintainAspectRatio: true,
   scales: {
      xAxes: [{
         ticks: {
            beginAtZero: true,
            max: 8
         },
         type: 'linear',
         position: 'bottom'
      }],
      yAxes: [{
         ticks: {
            beginAtZero: true,
            max: 16
         }
      }]
   }
};

var lineID = document.getElementById('linechart').getContext('2d');
var lineChart = new Chart(lineID, {
   type: 'scatter',
   data: linedata,
   options: chartOptions
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="linechart"></canvas>

Upvotes: 2

Related Questions