Plugins are functions that will be called for each chart that is created with the plugin enabled (specified in the plugins
configuration of a chart). The plugin function will be called with one argument which is the chart that is registering itself for the plugin. If you wish to use some additional parameters or configuration for your plugin initialization, it's recommended to use a function factory. You can check the example plugin for an implementation using a function factory.
function myChartistPlugin(chart) {
}
From the chart object options
, svg
(root SVG element) and the eventEmitter
can be used to manipulate the behaviour of the chart. It's the responsibility of the plugin to decide if it should be activated on a given chart (i.e. by checking the chart type chart instanceof Chartist.Line
etc.).
It's recommended to use the events of Chartist.js (like draw
) to manipulate the underlying elements. Using the events, plugins can chain up in a natural way and work independently on extending the functionality of the chart.
Plugins should contain their own default settings and use Chartist.extend
to override the settings specified in the options passed to the plugin factory function. Using the optionsProvider
of the chart object one could also implement functioanlity based on the chart configuration as well as responsive configuration.
Example Plugin
The following code shows an example plugin that is also available for download and installation. You can also use the repository of the example plugin to start your own awesome Chartist.js plugin.
function ctPointLabels(options) {
return function ctPointLabels(chart) {
var defaultOptions = {
labelClass: 'ct-label',
labelOffset: {
x: 0,
y: -10
},
textAnchor: 'middle'
};
options = Chartist.extend({}, defaultOptions, options);
if(chart instanceof Chartist.Line) {
chart.on('draw', function(data) {
if(data.type === 'point') {
data.group.elem('text', {
x: data.x + options.labelOffset.x,
y: data.y + options.labelOffset.y,
style: 'text-anchor: ' + options.textAnchor
}, options.labelClass).text(data.value);
}
});
}
}
}