Search code examples
javascriptreactjscanvasag-charts-reactag-charts

How I can manipulate with legend items on the chart from AgChartsReact?


I use a standalone chart from the Ag Grid library and want to manipulate manually which legend items should be shown/selected by default. I didn't find any specific API/property which can cover this use-case.

E.g., I want to see selected only the diesel legend item (and petrol should be shown unselected),

enter image description here

AgChartsReact always shows all legend items.

What did I investigate and try?

The chart is a canvas element, so I thought that it is possible to manipulate legend items from the canvas context, which I can get with useRef hook. But I cannot find how exactly it can be done and is it possible? Here is a ref to Plunker

UPD:

if someone is looking for how to store the data which legends is active or not, here is a function to get this (the same function you will find in Plunker):

const getLegendStatuses = () => {
const [changeEvent] = chartRef.current.chart.legend.allEventListeners.get("change");

const [, data] = changeEvent;

const [event] = data;
console.log(
  event.data.map(({ enabled, label }) =>  ({ label: label.text, enabled }))
);

}


Solution

  • I think you want to use visible: false on the Petrol series. This will still show up as greyed out in the legend, but you can click it to open it again.

    You can also add showInLegend: false if you want to remove it from the legend.

    If you want it greyed out in the legend but NOT clickable on the legend to make it visible, you might be able to make a custom listener for nodeClick, but I haven't tried that.