chartjs / chartjs/chartjs-plugin-datalabels

Request: add setting to show all labels above stacked bar

Open
#252 1 comment 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
JavaScript
Stars
920
Forks
507
PR merge metrics
No merged PRs in 30d

Description

Hi,

So I'm working on this project, where I'm showing percentages of stacked bar inside the bar. But when the bar is small, the text gets clipped or is not visible. So I figured those numbers should be put outside of the bar and colored based on the dataset. Having in mind all the alignment and anchoring options that this plugin has, an option to put labels outside of stacked bar should be implemented too.

Note: setting `anchor: 'end'` only puts the top bar label outside, and the one below move to the top one.

In the best case scenario it should work as follows:
- transfer both labels outside the stacked bar, when the height is limited (can be set by user maybe);
- make sure that both labels are in relation with each other, so they have same spacing and don't flow over each other;

The simplified version would simply add `anchor: 'outside'` setting and could leave all else for the user to set via functions.

Here is an image sample:
![Screenshot 2021-06-01 195106](https://user-images.githubusercontent.com/6840479/120362532-d9c08580-c313-11eb-9c97-23d7e58891c7.jpg)

This is the way I made this:
```
anchor: context => {
let bar = context.chart.getDatasetMeta(context.datasetIndex).data[context.dataIndex];
let barHeight = Math.abs(bar.y-bar.base);
const threshold = 7;
if (barHeight < threshold) {
return 'end';
}
return 'center';
}
```

In this code what I do is:
1. get the bar data;
2. calculate bar height from .y and .base params (height param is undefined);
3. set threshold (minimum height);
4. check for threshold.

Issue with this code is that it sets the lower bar label on the top bar, not above both bars. So I also use pretty much same code for `offset`, to calculate the height of top bar and offset first label by that height. Its a mess and does not work perfectly (spacing is off for different height bars). But a start.

```
offset: context => {
let bar = context.chart.getDatasetMeta(1).data[context.dataIndex];
let barHeight = Math.abs(bar.y-bar.base);
let offset = 10;
offset += barHeight;
return offset;
}
```

P.S. ChartJS 3, Datalabels 2.0 RC

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.