Back to Chart Js

Legend

docs/configuration/legend.md

4.5.18.9 KB
Original Source

Legend

The chart legend displays data about the datasets that are appearing on the chart.

Configuration options

Namespace: options.plugins.legend, the global options for the chart legend is defined in Chart.defaults.plugins.legend.

:::warning The doughnut, pie, and polar area charts override the legend defaults. To change the overrides for those chart types, the options are defined in Chart.overrides[type].plugins.legend. :::

NameTypeDefaultDescription
displaybooleantrueIs the legend shown?
positionstring'top'Position of the legend. more...
alignstring'center'Alignment of the legend. more...
maxHeightnumberMaximum height of the legend, in pixels
maxWidthnumberMaximum width of the legend, in pixels
fullSizebooleantrueMarks that this box should take the full width/height of the canvas (moving other boxes). This is unlikely to need to be changed in day-to-day use.
onClickfunctionA callback that is called when a click event is registered on a label item. Arguments: [event, legendItem, legend].
onHoverfunctionA callback that is called when a 'mousemove' event is registered on top of a label item. Arguments: [event, legendItem, legend].
onLeavefunctionA callback that is called when a 'mousemove' event is registered outside of a previously hovered label item. Arguments: [event, legendItem, legend].
reversebooleanfalseLegend will show datasets in reverse order.
labelsobjectSee the Legend Label Configuration section below.
rtlbooleantrue for rendering the legends from right to left.
textDirectionstringcanvas' defaultThis will force the text direction 'rtl' or 'ltr' on the canvas for rendering the legend, regardless of the css specified on the canvas
titleobjectSee the Legend Title Configuration section below.

:::tip Note If you need more visual customizations, please use an HTML legend. :::

Position

Position of the legend. Options are:

  • 'top'
  • 'left'
  • 'bottom'
  • 'right'
  • 'chartArea'

When using the 'chartArea' option the legend position is at the moment not configurable, it will always be on the left side of the chart in the middle.

Align

Alignment of the legend. Options are:

  • 'start'
  • 'center'
  • 'end'

Defaults to 'center' for unrecognized values.

Legend Label Configuration

Namespace: options.plugins.legend.labels

NameTypeDefaultDescription
boxWidthnumber40Width of coloured box.
boxHeightnumberfont.sizeHeight of the coloured box.
colorColorChart.defaults.colorColor of label and the strikethrough.
fontFontChart.defaults.fontSee Fonts
paddingnumber10Padding between rows of colored boxes.
generateLabelsfunctionGenerates legend items for each thing in the legend. Default implementation returns the text + styling for the color box. See Legend Item for details.
filterfunctionnullFilters legend items out of the legend. Receives 2 parameters, a Legend Item and the chart data.
sortfunctionnullSorts legend items. Type is : sort(a: LegendItem, b: LegendItem, data: ChartData): number;. Receives 3 parameters, two Legend Items and the chart data. The return value of the function is a number that indicates the order of the two legend item parameters. The ordering matches the return value of Array.prototype.sort()
pointStylepointStyle'circle'If specified, this style of point is used for the legend. Only used if usePointStyle is true.
textAlignstring'center'Horizontal alignment of the label text. Options are: 'left', 'right' or 'center'.
usePointStylebooleanfalseLabel style will match corresponding point style (size is based on pointStyleWidth or the minimum value between boxWidth and font.size).
pointStyleWidthnumbernullIf usePointStyle is true, the width of the point style used for the legend.
useBorderRadiusbooleanfalseLabel borderRadius will match corresponding borderRadius.
borderRadiusnumberundefinedOverride the borderRadius to use.

Legend Title Configuration

Namespace: options.plugins.legend.title

NameTypeDefaultDescription
colorColorChart.defaults.colorColor of text.
displaybooleanfalseIs the legend title displayed.
fontFontChart.defaults.fontSee Fonts
paddingPadding0Padding around the title.
textstringThe string title.

Legend Item Interface

Items passed to the legend onClick function are the ones returned from labels.generateLabels. These items must implement the following interface.

javascript
{
    // Label that will be displayed
    text: string,

    // Border radius of the legend item.
    // Introduced in 3.1.0
    borderRadius?: number | BorderRadius,

    // Index of the associated dataset
    datasetIndex: number,

    // Fill style of the legend box
    fillStyle: Color,

    // Text color
    fontColor: Color,

    // If true, this item represents a hidden dataset. Label will be rendered with a strike-through effect
    hidden: boolean,

    // For box border. See https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap
    lineCap: string,

    // For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash
    lineDash: number[],

    // For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset
    lineDashOffset: number,

    // For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin
    lineJoin: string,

    // Width of box border
    lineWidth: number,

    // Stroke style of the legend box
    strokeStyle: Color,

    // Point style of the legend box (only used if usePointStyle is true)
    pointStyle: string | Image | HTMLCanvasElement,

    // Rotation of the point in degrees (only used if usePointStyle is true)
    rotation: number
}

Example

The following example will create a chart with the legend enabled and turn all the text red in color.

javascript
const chart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        plugins: {
            legend: {
                display: true,
                labels: {
                    color: 'rgb(255, 99, 132)'
                }
            }
        }
    }
});

Custom On Click Actions

It can be common to want to trigger different behaviour when clicking an item in the legend. This can be easily achieved using a callback in the config object.

The default legend click handler is:

javascript
function(e, legendItem, legend) {
    const index = legendItem.datasetIndex;
    const ci = legend.chart;
    if (ci.isDatasetVisible(index)) {
        ci.hide(index);
        legendItem.hidden = true;
    } else {
        ci.show(index);
        legendItem.hidden = false;
    }
}

Let's say we wanted instead to link the display of the first two datasets. We could change the click handler accordingly.

javascript
const defaultLegendClickHandler = Chart.defaults.plugins.legend.onClick;
const pieDoughnutLegendClickHandler = Chart.controllers.doughnut.overrides.plugins.legend.onClick;
const newLegendClickHandler = function (e, legendItem, legend) {
    const index = legendItem.datasetIndex;
    const type = legend.chart.config.type;

    if (index > 1) {
        // Do the original logic
        if (type === 'pie' || type === 'doughnut') {
            pieDoughnutLegendClickHandler(e, legendItem, legend)
        } else {
            defaultLegendClickHandler(e, legendItem, legend);
        }

    } else {
        let ci = legend.chart;
        [
            ci.getDatasetMeta(0),
            ci.getDatasetMeta(1)
        ].forEach(function(meta) {
            meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
        });
        ci.update();
    }
};

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        plugins: {
            legend: {
                onClick: newLegendClickHandler
            }
        }
    }
});

Now when you click the legend in this chart, the visibility of the first two datasets will be linked together.