score:5

Accepted answer

to have functional pan and zoom on your ng2-charts, this is what you need to do:

  1. use npm to install the dependencies: hammerjs and chartjs-plugin-zoom
  2. import the dependencies to your module.
  3. add the pan and zoom configurations in the plugin section of the chart configuration.
  4. horizontal zoom and pan only works with scatter charts

it is easier said than done so, before adding zoom and pan, be sure that you have a working ng2-chart in your project. otherwise you never know what's going wrong.

1. install the required plugins

execute the following commands in the root folder of your project:

   npm install hammerjs
   npm install charts-plugin-zoom

2. import the plugins into your module

after installing the plugins, you can check that these two folders exist:

  • node_modules/hammerjs
  • node_modules/chartjs-plugin-zoom

you need to include them in your module. for example, you can add two imports in app.module.ts:

   import 'hammerjs';
   import 'chartjs-plugin-zoom';

   @ngmodule({
     declarations: [
       appcomponent,
       ...
     ]
   }

as you can see, no need to add anything in the declarations or any of the other sections of the @ngmodule annotation.

3. add the zoom options in chart configuration to setup a chart with ng2-chart you had to create a template with something like the following snippet:

  <canvas basechart
      charttype="bar"
      [datasets]="datasets"
      [labels]="labels"
      [options]="options"
      legend="true">
  </canvas>

add, in the corresponding class, a plugin element with zoom section. mind the zoom nested twice:

import { chartdatasets, chartoptions } from 'chart.js';
...
...
export class yourchartcomponent {
  ...
  public options: chartoptions = {
      legend: {
        ...
      },
      scales: {
         ...
      },
      plugins: {
        zoom: {
          pan: {
            enabled: true,
            mode: 'xy'
          },
          zoom: {
            enabled: true,
            mode: 'xy'
          }
        }
      }
    };
  ...
  ...
}

4. horizontal pan only works with scatter charts

typically, the example above will only pan and zoom vertically.

some links

credits to where i got the information:


Related Query

More Query from same tag