ChartJS使用散点图缩放刻度

时间:2017-06-10 17:32:46

标签: chart.js

我刚开始使用ChartJS。我正在探索版本2.6中的新散点图,并希望以0:0开始X-Y图的原点。我还想指定X和Y的最大值。

不幸的是,将beginAtZero设置为true并为每个轴设置最大值似乎不起作用。示例代码如下:

    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);

这仍然以一条线(散点图)结束,从X = 1开始,Y = 2,以X = 7,Y = 14(而不是0:0到8:16)结束。

1 个答案:

答案 0 :(得分:1)

您正在错误地配置图表。以下是它应该如何创建......



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>
&#13;
&#13;
&#13;