[Chartjs]-Different styles in ticks on ChartJS

3👍

You can make use of the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code snippet, I use the afterDraw hook to draw text of different styles underneath each bars.

Note that no computation of text size is needed when composing your own labels labels. You can simply add a space to the first text section and use ctx.textAlign ‘right’, then use ctx.textAlign ‘left’ for drawing the second text section.

When drawing your own tick labels, you need to instruct Chart.js not to display the default labels. This can be done through the following definition inside the chart options.

scales: {
  xAxes: [{
    ticks: {
      display: false
    }
  }], 

You also need to define some padding for the bottom of the chart, otherwise you won’t see your custom tick labels.

layout: {
  padding: {
    bottom: 20
  }
},
new Chart(document.getElementById('myChart'), {
  type: 'bar',
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      ctx.save();
      chart.data.labels.forEach((l, i) => {
        var value = chart.data.datasets[0].data[i];
        var x = xAxis.getPixelForValue(l);
        ctx.textAlign = 'right';
        ctx.font = '12px Arial';
        ctx.fillText(l + ' ', x, yAxis.bottom + 18);
        ctx.textAlign = 'left';
        ctx.font = 'bold 14px Arial';
        ctx.fillStyle = 'blue';
        ctx.fillText(value, x, yAxis.bottom + 17);
      });
      ctx.restore();
    }
  }],
  data: {
    labels: ['Error', 'Warn', 'Info'],
    datasets: [{
      label: 'My First Dataset',
      data: [30, 59, 80],
      fill: false,
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 205, 86, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)'],
      borderWidth: 1
    }]
  },
  options: {
    layout: {
      padding: {
        bottom: 20
      }
    },
    scales: {
      xAxes: [{
        ticks: {
          display: false
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
canvas {
  max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" width="10" height="5"></canvas>

Leave a comment