victory icon indicating copy to clipboard operation
victory copied to clipboard

Stacked Bar Charts - center label on Bar Segment

Open jonashaefele opened this issue 4 years ago • 3 comments

Bugs and Questions

Checklist

  • [x] This is not a victory-native specific issue. (Issues that only appear in victory-native should be opened here)

  • [x] I have read through the FAQ and Guides before asking a question

  • [x] I am using the latest version of Victory

  • [x] I've searched open issues to make sure I'm not opening a duplicate issue

The Problem

In a stacked bar chart, I'm trying to add labels to each bar segment on top of the bar. Sort of like this: Screenshot 2019-11-14 at 13 16 12

When adding labels to a stacked bar chart, the label for each chart segment seems to render "after" the segment, on top of the beginning of the next segment like this instead:

Screenshot 2019-11-14 at 13 34 51

I'm really struggling to figure out how to center the labels over each segment. As the labels are their own elements and not children to the bar segments they belong to.

I played around with all combinations of textAnchor and verticalAnchor and ended up at a bit of a hacky solution where I calculate the offset based on domain range and chart width. But it's still a bit off...

Any ideas on how to center the labels? Maybe I just missed something simple?

Reproduction

Sandbox based on the 100% column stacked bar example here:

https://codesandbox.io/s/basic-victory-example-yx95d

The main part being:

labelComponent={
  <VictoryLabel
    dx={data => {
      // (graphWidth / (maxDomain-minDomain)) * (datum.y / 2)
      // ^scale factor percent to pixels  * half the width of segment in %
      return (-(400 - 2*30) / (100 - 0)) * data.datum.y/2;
    }}
  />
}

Is there any less hacky way to achieve the same?

Thanks!

jonashaefele avatar Nov 14 '19 13:11 jonashaefele