I am using chartjs v4. I am modifying the legend text. I see code gets executed but the legend text does not change. Here is the code:
var myChart = new Chart(ctx, {
type: 'bar',
plugins: [{
afterLayout: chart => {
chart.legend.legendItems.forEach(
(label) => {
label.text += ' Test';
return label;
}
)
}
}],
...
The legend labels remain the same (It does not add "Test" at the end of each label). What am I missing? Something is not being refreshed somehow.
UPDATE/SOLUTION
First I used afterDraw and that worked. But Kikon's solution was even better. I noticed that afterDraw was executing twice and therefore updating the legend labels twice unnecessarily. I am going to use Kikon's solution and use afterUpdate instead of afterDraw:
var myChart = new Chart(ctx, {
type: 'bar',
plugins: [{
afterUpdate: (chart, args, opts) => {
chart.legend.legendItems.forEach(
(label) => {
label.text += ' Test ';
return label;
}
)
}
}],
...
The labels are re-built in the legend plugin's
afterUpdate(source code), which is called later thanafterLayout; so, there are two possibilities:afterUpdaterather than inafterLayoutafterUpdateto avoid the redundant legend items recompute:As discussed with Robert Smith in comments,
afterUpdate(from the first solution above) is the earliest called plugin hook that can be used to change the label texts. Any of the render process hooks (frombeforeRendertoafterRender) could also be used.I'd add here, for reference, that there is another method to adjust the legend labels dynamically, which is to customize the
generateLabelsfunction of theoptions.plugins.legend.labelsnamespace. The difficulty with it is that it should return several options for the legend item (see Legend Item Interface) that one is not concerned with here. To avoid that, one might call the defaultgenerateLabelsfunction first: