I have 3 charts on a component in my angular app.
I need to create text label plugins to show on the chart. Each chart needs to have specific plugin assigned to it. I have searched a lot and could not find any solution.
As of now i am registering the plugins globally with Chart.register()
which is making the appearance undesirable because all of the label plugins gets applied to all of the charts.
is there any way to apply specific plugins to specific charts?
I am using ng2-charts and defining my charts like with BaseChartDirective.
@ViewChildren(BaseChartDirective) charts?: QueryList<BaseChartDirective>;
I am creating plugins like this
function createLabelPlugin(text: string, xPosition: number, yPosition: number) {
return {
id: 'customLabelPlugin',
afterDraw(chart: any) {
const ctx = chart.ctx;
ctx.save();
ctx.font = 'bold 16px Arial';
ctx.fillStyle = 'black';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Draw the text at the specified position
ctx.fillText(text, xPosition, yPosition);
ctx.restore();
}
};
}
The ng2-charts
has library has an @Input
parameter named plugins
where you can supply the plugin that you want to set for a particular chart.
export class BaseChartDirective<
TType extends ChartType = ChartType,
TData = DefaultDataPoint<TType>,
TLabel = unknown,
>
implements OnDestroy, OnChanges
{
...
@Input() public plugins: Plugin<TType>[] = [];
To use it, just add the plugin as below.
export class LineComponent {
plugins = [createLabelPlugin('qwerty', 0, 0)];
<canvas baseChart [type]="chartType" [data]="data" [options]="options" [plugins]="plugins">
</canvas>
if you are dealing with data labels, I recommend chartjs-plugin-datalabels, great for displaying labels on charts.