Chartjs-How to set subscript text in Chart.js axis title

0👍

You can use 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 the title using two different fonts.

Assuming you want to draw the x-axis title, please note that inside chart options, I also defined some layout padding. This prevents the title from overlapping the chart.

layout: {
  padding: {
    bottom: 20
  }
},

Please take a look at the runnable code below and see how it works.

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      ctx.textAlign = 'right';
      ctx.font = '12px Arial';
      ctx.fillStyle = 'gray';
      ctx.fillText('Q/P', chart.chart.width / 2, chart.chart.height -14);
      ctx.textAlign = 'left';
      ctx.font = '8px Arial';
      ctx.fillText('b inst', chart.chart.width / 2, chart.chart.height - 10);
      ctx.restore();
  }
  }],
  data: {
    labels: ['A', 'B', 'C', 'D'],
    datasets: [{
      data: [10, 12, 8, 6],
      backgroundColor: ['red', 'blue', 'green', 'orange']
    }]
  },
  options: {
    layout: {
      padding: {
        bottom: 20
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment