[Chartjs]-Is there a way to adjust only the bottom padding of a chart's title in Chart.js?

3👍

title.padding takes the number of pixels to add above and below the title text.

There exists a workaround to add padding at the bottom of the chart title only. The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw the title yourself directly on the canvas using CanvasRenderingContext2D.fillText().

plugins: [{
  afterDraw: chart => {
    var ctx = chart.chart.ctx;
    ctx.save();
    ctx.textAlign = 'center';
    ctx.font = "18px Arial";
    ctx.fillStyle = "gray";
    ctx.fillText('My Title', chart.chart.width / 2, 20);
    ctx.restore();
  }
}],

Together with this, you’ll have to define top padding for your chart. This determines the space between your title and the chart (the title bottom padding basicaly).

layout: {
  padding: {
    top: 80
  }
},  

Please have a look at below code that shows how it could look like.

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      ctx.textAlign = 'center';
      ctx.font = "18px Arial";
      ctx.fillStyle = "gray";
      ctx.fillText('My Title', chart.chart.width / 2, 20);
      ctx.restore();
    }
  }],
  data: {
    labels: ['A', 'B', 'C', 'D'],
    datasets: [{
      data: [10, 12, 8, 6],
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 205, 86, 0.2)', 'rgba(75, 192, 192, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)'],
      borderWidth: 1
    }]
  },
  options: {
    layout: {
      padding: {
        top: 80
      }
    },   
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>

Leave a comment