Jens Törnell
Jens Törnell

Reputation: 24768

Chart js multiple titles

Is it possible to have multiple titles in Chart JS? https://www.chartjs.org/

At the current state I use the title as a description below the chart. I also need a title on top of the chart. Is it possible?

An alternative for my case would be if there was another way to implement a description at the bottom and keep the title as top title.

var chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        title: {
            display: true,
            text: 'Custom Chart Title',
            position: 'bottom',
        }
    }
});

Upvotes: 1

Views: 1736

Answers (1)

uminder
uminder

Reputation: 26150

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 a title on the canvas. That way you can draw as many titles as you want, define them of different style each and place them wherever it suits you.

Please note that inside chart options, I also defined some layout padding. This prevents the title from overlapping the chart bars.

layout: {
  padding: {
    top: 40
  }
}

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

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: ['A', 'B', 'C', 'D'],
    datasets: [{
      data: [10, 12, 8, 6],
      backgroundColor: ['red', 'blue', 'green', 'orange']
    }]
  },
  options: {
    layout: {
      padding: {
        top: 40
      }
    },
    title: {
      display: true,
      text: 'Custom Chart Title',
      position: 'bottom',
    },
    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>

Upvotes: 2

Related Questions