Chart.js plugin to provide keyboard navigation to legends
npm install chartjs-plugin-a11y-legendjs
import {Chart} from "chart.js/auto";
import plugin from "chartjs-plugin-a11y-legend";
Chart.register(plugin);
`
That will register the plugin globally. Alternatively, if you want to enable for a given chart, you can do this:
`js
import {Chart} from "chart.js/auto";
import plugin from "chartjs-plugin-a11y-legend";
new Chart(canvasElement, {
type: "bar",
data: {
datasets: [{
data: [1,4,2,8]
}]
},
plugins: [plugin]
});
`
Available options
The following pluing options are available:
* margin - (pixels) Add some margin to the bounding box that will appear around your legend items. Default: 4.
Here's an example for adding your own options:
`js
import {Chart} from "chart.js/auto";
import plugin from "chartjs-plugin-a11y-legend";
new Chart(canvasElement, {
type: "bar",
data: {
datasets: [{
data: [1,4,2,8]
}]
},
options: {
plugins: {
a11y_legend: {
margin: 0
}
}
},
plugins: [plugin]
});
`
Using react-chartjs-2
The plugin will also work with react-chartjs-2.
`jsx
import React from "react";
import {Chart, registerables} from "chart.js";
import {Bar} from "react-chartjs-2";
import a11yLegend from "chartjs-plugin-a11y-legend";
// Register what you want for chart.js
Chart.register(...registerables);e
// Register the a11y legend plugin, so that it can apply to every chart
Chart.register(a11yLegend);
// Here's a sample chart using react-chartjs-2
export default function App(){
return <>
data={{
labels: ["A","B","C","D"],
datasets: [
{
label: "Green",
data: [9,3,5,1]
},
{
label: "Red",
data: [5,6,2,8]
}
]
}}
/>
>
}
``