chartjs / chartjs-plugin-datalabels

Chart.js plugin to display labels on data elements
https://chartjs-plugin-datalabels.netlify.app
MIT License
863 stars 459 forks source link

Feature Request: option to handle when label cannot fit inside a bar #395

Open getify opened 9 months ago

getify commented 9 months ago

I have a bar chart (horizontal in this case, but vertical would be the same thing) where I want the labels to sit right inside the end (right or top) of the bar.

So I use anchor: 'end' and then position: 'left' (or position: 'start'). For most bars, this works fine. But if a bar is rendering quite short, then the label looks ugly overlapping the axis, and possibly even being cut off. So in those cases, I want the label outside the bar, with anchor: 'end' and position: 'right' / position: 'end'.

I've tried defining align as a function, so I can programmatically give different values. The problem is, I can't really reliably "compute" whether the label could fit or not. The context object that's passed in gives me the plotted dataset value, but it doesn't really tell me the relative dimensions of the bar versus the label.

A solution that might work is to be able to pass an array of values, like position: [ 'left', 'right' ] or position: [ 'start', 'end' ], and the library tries to position with the first value, and if it doesn't fit, or overlaps, or whatever... then it tries the next value, and so on.

Even more simply, maybe n position: 'auto' could cycle from 'left' > 'center' > 'right' (or 'start' > 'center' > 'end'), trying each position until the label can fit?

jcorevnue2022 commented 1 month ago

+1