Chartjs-Chart JS add max value to legend

1👍

Yes, it is possible to show the max value for each dataset inside the legend. You can use the legend.labels.generateLabels config property to do this.

This property allows you to define your own function that generates the legend labels. To add the max, we simply iterate through each dataset’s data array, find the max, and build it into the label string.

Here is an example configuration. The magic happens when we set the text property in the return.

legend: {
  display: true,
  position: 'bottom',
  labels: {
    generateLabels: function(chart) {
      var data = chart.data;
      return Chart.helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {

        return {
          text: dataset.label + " (Max Value: " + Chart.helpers.max(dataset.data).toLocaleString() + ")",
          fillStyle: (!Chart.helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
          hidden: !chart.isDatasetVisible(i),
          lineCap: dataset.borderCapStyle,
          lineDash: dataset.borderDash,
          lineDashOffset: dataset.borderDashOffset,
          lineJoin: dataset.borderJoinStyle,
          lineWidth: dataset.borderWidth,
          strokeStyle: dataset.borderColor,
          pointStyle: dataset.pointStyle,

          // Below is extra data used for toggling the datasets
          datasetIndex: i
        };
      }, this) : [];
    },
  },
},

I also created a codepen to demonstrate this.

Leave a comment