Reputation: 509
I'm trying to align the title to the left instead of the center (shown in the image).
I know this is possible on chartJS v3.0.0-alpha.2
, but reactchartjs
only goes up to 2.9.30
as far as I know.
Does anyone know how to achieve this in reactchartjs
?
I thought it would be something like:
options={{
title: {
position: 'top',
align: 'left',
},
}}
Any help would be appreciated.
Upvotes: 2
Views: 3814
Reputation: 9583
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:
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
:
Upvotes: 2
Reputation: 26150
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.
Upvotes: 1