[Chartjs]-Chart.js Adapting different X axis with same scale

1๐Ÿ‘

โœ…

2 approaches, you can add a second x scale that you hide to which you link your dataset with lesser entries like so:

const data = {
  labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
  datasets: [{
      label: 'full data',
      //Xaxis = [1,2,3,4,5,6,7,8,9,10,11,12]
      data: [2, 3, 4, 3, 2, 3, 4, 5, 6, 5, 4, 5],
      borderColor: ['rgba(75, 192, 192, 1)'], //green
      yAxisID: 'y1'
    },
    {
      label: 'stacked data',
      //Xaxis = [1,4,7,10]
      data: [2, 3, 4, 3], //one every three points of full data, but they start from 1
      borderColor: ['rgba(255, 99, 132, 1)'], //red
      stepped: true,
      yAxisID: 'y2',
      xAxisID: 'x2'
    },
  ]
}

const config = {
  type: 'line',
  data: data,
  options: {
    interaction: {
      intersect: false,
      mode: 'index',
    },
    pointRadius: 0,
    scales: {
      y1: {
        min: 0,
        stack: 'demo'
      },
      y2: {
        min: 0,
        stack: 'demo'
      },
      x: {},
      x2: {
        display: false,
        labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].filter((e, i) => i % 3 === 0) // Generate labels array for only every third element
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const myChart = new Chart(ctx, config);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

Or you can use object notation for your dataset to link to the correct x axis label:

const data = {
  labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
  datasets: [{
      label: 'full data',
      //Xaxis = [1,2,3,4,5,6,7,8,9,10,11,12]
      data: [2, 3, 4, 3, 2, 3, 4, 5, 6, 5, 4, 5],
      borderColor: ['rgba(75, 192, 192, 1)'], //green
      yAxisID: 'y1'
    },
    {
      label: 'stacked data',
      //Xaxis = [1,4,7,10]
      data: [{
        x: 1,
        y: 2
      }, {
        x: 4,
        y: 3
      }, {
        x: 7,
        y: 4
      }, {
        x: 10,
        y: 3
      }], //one every three points of full data, but they start from 1
      borderColor: ['rgba(255, 99, 132, 1)'], //red
      stepped: true,
      yAxisID: 'y2'
    },
  ]
}

const config = {
  type: 'line',
  data: data,
  options: {
    interaction: {
      intersect: false,
      mode: 'index',
    },
    pointRadius: 0,
    scales: {
      y1: {
        min: 0,
        stack: 'demo'
      },
      y2: {
        min: 0,
        stack: 'demo'
      },
      x: {}
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const myChart = new Chart(ctx, config);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

Leave a comment