Jean Nobrega
Jean Nobrega

Reputation: 23

How to make Chart.js scatter x-axis chart begin and end exactly at minimum/maximum dataset value

I have a chart.js scatter template that i´m creating in node-red to display a 10-sample realtime sliding window chart. Below is the code of random generated data, where the x-axis is timestamp.

<canvas id="line-chart3" width="800" height="450"></canvas>
<script>
  
new Chart(document.getElementById("line-chart3"), {
  type: 'scatter',
  data: {
    
    datasets: [{label:"ds1",data:[{x:1677246631553,y:31},{x:1677246631840,y:17},{x:1677246632077,y:31},{x:1677246632329,y:42},{x:1677246632552,y:38},{x:1677246632792,y:7},{x:1677246633017,y:13},{x:1677246633237,y:17},{x:1677246633472,y:35},{x:1677246633705,y:4}],backgroundColor:"#009900",borderColor:"#009900",steppedLine:false,fill:false,borderWidth:1}] 
      
  },
  options: {
    animation: false,
    scales: {
      x: {
        offset: false,
        ticks: {
          major: {
            enabled: false,
          },

        },
      }
    },

     
    
    title: { 
      display: true,
      text: 'Teste de grafico',
      
    }
  }
});
</script>

But the chart is displaying like the figure below:

chart.js scatter chart

I wish to make the x-axis begin exactly at {x:1677246631553,y:31} and end exacly at {x:1677246633472,y:35} (min and max of data array) and no at the grid major ticks.

I use dynamic data generated from node-red msg.payload, so, hardcoded min and max values to the x-axis is not possible.

I've tried with offset, major tick disabled and various other options. None of them seems to work.

Thanks in advance for any help

Jean

Upvotes: 1

Views: 803

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31421

You can specify a min and max on your scale options:

let data = [
          { x: 1677246631553, y: 31 },
          { x: 1677246631840, y: 17 },
          { x: 1677246632077, y: 31 },
          { x: 1677246632329, y: 42 },
          { x: 1677246632552, y: 38 },
          { x: 1677246632792, y: 7 },
          { x: 1677246633017, y: 13 },
          { x: 1677246633237, y: 17 },
          { x: 1677246633472, y: 35 },
          { x: 1677246633705, y: 4 }
        ] 
let ctx = document.getElementById("myChart");
let myChart = new Chart(ctx, {
  type: "scatter",
  data: {
    datasets: [
      {
        label: "ds1",
        data: data,
        backgroundColor: "#009900",
        borderColor: "#009900",
      }
    ]
  },
  options: {
    animation: false,
    scales: {
      x: {
        min: data[0].x,
        max: data[data.length - 1].x,
      }
    }
  }
});
<script src="https://npmcdn.com/[email protected]/dist/chart.umd.js"></script>
<div class="myChartDiv">
  <canvas id="myChart" width="600" height="400"></canvas>
</div>

Upvotes: 1

Related Questions