[Chartjs]-Align Title Left React Chart.js V2

2👍

You should use the align parameter. This sets the alignment of the title. Your options are:

  • start
  • center
  • end

Your align: 'left' isn’t one of the above and will not have any effect. Setting align: 'start' however will give you exactly what you want:

enter image description here

The full code looks like this:

<Chart 
    type='line' 
    data={dat} 
    options={{
        plugins: {
            title: {
                display: true,
                align: 'start',
                text: 'Bitcoin Mining Difficulty'
            }
        }
    }} />

Let me also mention that you should not confuse that with position: 'left'. position moves the whole title into one of top, left, bottom, right area of the chart. An example with a combination of position: 'left' and align: start:

enter image description here

1👍

The Chart.js 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().

In React, you can register the plugin as follows:

componentWillMount() {
  Chart.pluginService.register({
    afterDraw: chart => {
      let ctx = chart.chart.ctx;
      ctx.save();
      let xAxis = chart.scales['x-axis-0'];
      ctx.textAlign = "left";
      ctx.font = "14px Arial";
      ctx.fillStyle = "black";
      ctx.fillText("Title", xAxis.left, 10);
      ctx.restore();
    }
  });
} 

You’ll also have to define some extra padding at the top of the chart to make sure, the title appears on the canvas.

options: {
  layout: {
    padding: {
      top: 20
    }
  }, 
  ...

Please take a look at this StackBlitz and see how it works.

Leave a comment