[Chartjs]-ChartJS multiple X axis and extra labels in y axis

3👍

For the X axis on top you can just add another X axis and set position to top, for the labels between the Y axis best is to write a custom plugin for that.

Example:

var options = {
  type: 'line',
  data: {
    labels: ["A", "B", "C", "D", "E", "F"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      x: {
        position: 'bottom',
        grid: {
          offset: true // offset true to get labels in between the lines instead of on the lines
        }
      },
      x2: {
        position: 'top',
        grid: {
          offset: true // offset true to get labels in between the lines instead of on the lines
        }
      },
      y: {
        ticks: {
          count: (context) => (context.scale.chart.data.labels.length + 1)
        }
      }
    },
    plugins: {
      labelsY: {
        font: 'Arial',
        size: '14px',
        color: '#666',
        align: 'right',
        reverseLabels: false // true to make A start at top and F at bottom
      }
    }
  },
  plugins: [{
    id: 'labelsY',
    afterDraw: (chart, args, options) => {
      const {
        ctx,
        scales: {
          y,
          x
        },
        data: {
          labels
        }
      } = chart;

      let dupLabels = JSON.parse(JSON.stringify(labels)); // remove pointer to internal labels array so you dont get glitchy behaviour

      if (options.reverseLabels) {
        dupLabels = dupLabels.reverse();
      }

      dupLabels.forEach((label, i) => {
        ctx.save();

        ctx.textAlign = options.align || 'right';
        ctx.font = `${options.size || '20px'} ${options.font || 'Arial'}`;
        ctx.fillStyle = options.color || 'black'

        let xPos = x.getPixelForValue(labels[0]) - ctx.measureText(label).width;
        let yPos = (y.getPixelForValue(y.ticks[i].value) + y.getPixelForValue(y.ticks[i + 1].value)) / 2;

        ctx.fillText(label, xPos, yPos)

        ctx.restore();
      });
    }
  }]
}

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

Leave a comment