Hello,
I have a chart, i am adding an image of it. Is there a chance to hide zero values on bars ?
You can use scriptable options (example):
options: {
plugins: {
datalabels: {
display: function(context) {
return context.dataset.data[context.dataIndex] !== 0; // or >= 1 or ...
}
}
}
}
Thank you very much !
I used return context.dataset.data[context.dataIndex] > 1; because i wanted to hide zeros. It's working very well.
You right, my snippet was wrong (edited), it should return true if data !== 0 (or >= 1).
Awesome! Thanks!
Would it make sense to add this as an official configurable option, since I imagine it's incredibly common?
@davidklebanoff I designed scriptable options to actually avoid introducing stuff like hideWhenZero which are IMO use case oriented instead of generic options. Adding it built in would require more processing code to guess the actual value and thus more code to maintain for something really easy to implement on the user end. It's also a door opened to options like: colorAtZero, backgroundAtZero, colorWhenNegative, etc. So no, it doesn't make sense to me and I will likely reject any related PR.
If you need this behavior for all your charts, you can setup a global option:
Chart.defaults.global.plugins.datalabels.display = function(ctx) {
return ctx.dataset.data[ctx.dataIndex] !== 0;
}
You can also easily implement this option yourself in your projects:
Chart.defaults.global.plugins.datalabels.display = function(ctx) {
var opts = ctx.chart.options.plugins.datalabels;
return opts.hideWhenZero
? ctx.dataset.data[ctx.dataIndex] !== 0
: undefined;
}
Something I could maybe consider however is to expose the value in the context:
Chart.defaults.global.plugins.datalabels.display = function(ctx) {
return ctx.value !== 0;
}
What about hiding when the label can't be completely displayed? I'm thinking of a measureText call on the canvas ct in the display callback, but I can't find a piece of data that tells me how big the bar (my chart is a vertical bar chart) for the current index is. Any suggestion?
I'm using Ruby on Rails with chartkick to construct Chart.js calls server-side. That method uses Ruby hashes for configuration (which later get translated to Javascript) and it's not clear how to inject javascript functions using this method. As this is a fairly common use case, I second the request to have "hiding zeroes" as an option. Thanks for considering!
Most helpful comment
You can use scriptable options (example):