Chartjs-plugin-datalabels: Showing/Hiding Based on Visibility of Lines in Chart

Created on 19 Apr 2018  路  12Comments  路  Source: chartjs/chartjs-plugin-datalabels

I have a line chart with a legend and 3 lines drawn. When you click the legend the lines show/hide and the graph adjusts accordingly. Out of the box the datalabels do not hide whenever a line is hidden. I am currently using this method of hiding the datalabels:

options: {
    plugins: {
        datalabels: {
            display: (context: any) => {
                return !context.dataset._meta[0].hidden;
            },
        },
    },
},

This works, but the _meta[0].hidden thing seems like a hack/not something we're supposed to be using. Is there a different approach that is more stable?

bug resolved

Most helpful comment

That's a bug, will be fixed in next release (labels will always be hidden if the dataset is hidden).

As a workaround, you can use:

display: function (context) {
    return context.chart.isDatasetVisible(context.datasetIndex);
}

EDIT: remove TypeScript

All 12 comments

I think that's a bug, it should work out of the box.

Can you build a jsfiddle that reproduces this issue?

The same issue form me, the wjohnsto solutions works, Chart.js Version: 2.7.2 used.

datalabelerror

Please, is there another solution?

Here is a jsfiddle: https://jsfiddle.net/sxzqwr80/76/

That's a bug, will be fixed in next release (labels will always be hidden if the dataset is hidden).

As a workaround, you can use:

display: function (context) {
    return context.chart.isDatasetVisible(context.datasetIndex);
}

EDIT: remove TypeScript

It's nice!, thanks.

Sweet 馃憤

Thanks 馃槏

Thanks. And I use this for display data with condition

display: function(context) {
    return context.chart.isDatasetVisible(context.datasetIndex)
        && context.dataset.data[context.dataIndex] > 0;
}

Edit(SB): code formatting

My code is TypeScript, so you may have to remove the non-JS stuff to get it to work.

display: function (context) {
    return context.chart.isDatasetVisible(context.datasetIndex);
}

@wjohnsto Thanks (I updated my comment)

Fixed in 542ec921, will be released in 0.4.0

Was this page helpful?
0 / 5 - 0 ratings

Related issues

aldipower picture aldipower  路  7Comments

LeoDupont picture LeoDupont  路  11Comments

jedskie picture jedskie  路  6Comments

dgambin picture dgambin  路  5Comments

012attack picture 012attack  路  8Comments