Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js - Where do I find which components should be registered?

I'm new to Chart.js, saw the v3 doc:

Chart.js 3 is tree-shakeable, so it is necessary to import and register the controllers, elements, scales, and plugins you are going to use.

I'm wondering where do I find these things for registering, for example, what needs to be registered for this example to work?

like image 226
Wenfang Du Avatar asked Nov 25 '20 10:11

Wenfang Du


People also ask

How do I use Chartjs plugins?

Plugins can be shared between chart instances: const plugin = { /* plugin implementation */ }; // chart1 and chart2 use "plugin" const chart1 = new Chart(ctx, { plugins: [plugin] }); const chart2 = new Chart(ctx, { plugins: [plugin] }); // chart3 doesn't use "plugin" const chart3 = new Chart(ctx, {}); Copied!


2 Answers

You will get an error in your console if you use something that is not imported. If you want to be sure you just have everything and throw away the benefit of tree-shaking you can use this import and register:

import { Chart, registerables } from 'chart.js'

Chart.register(...registerables)

Or in one line:

import Chart from 'chart.js/auto'

For the example to work, the elements that need to be imported and registered are:

  • barController
  • barElement
  • categoryScale
  • Tooltip
  • Legend

Generally speaking for a chart you need its controller so lineController for line chart, pieController for a pie chart, etc. You need the element so a lineElement and pointElement for line or radar chart, arcElement for pie, doughnut or polar area chart, and barElement for bar chart. And then you need to import the supplied plugins for the title, filler (for area charts), legend, and the tooltip.

like image 99
Wenfang Du Avatar answered Oct 21 '22 22:10

Wenfang Du


Maybe is a little late, but if you are using npm, you can register everything from chart.js using

import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);

Or, directly:

import Chart from 'chart.js/auto';

Also, you can see here everything it can be imported for an especific chart, and my answer above: https://www.chartjs.org/docs/master/getting-started/integration.html#bundlers-webpack-rollup-etc

like image 34
Alberto Camino Avatar answered Oct 21 '22 22:10

Alberto Camino