Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Totals for stacked bars #2020

Closed
ghost opened this issue May 27, 2022 · 10 comments
Closed

Totals for stacked bars #2020

ghost opened this issue May 27, 2022 · 10 comments
Labels

Comments

@ghost
Copy link

ghost commented May 27, 2022

Is your feature request related to a problem? Please describe.
I don't know if there is a way to show the totals of stacked bars as asked in

Describe the solution you'd like
Being able to show the total of the portions of the stacked bar over the bars or as the number of the last segment.

Additional context
I opened this issue, because there is a closed similar issue (#951) where the last message says: "Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!"

I personally need a solution to this in a project I'm working and I suspect other people are looking for one too.

@ghost
Copy link
Author

ghost commented May 27, 2022

I mention @Mulli and @timothyarmes who asked for this feature in the other issue (#951).

@Mulli
Copy link

Mulli commented May 27, 2022

@damianocasula I am still waiting for a solution... Thanks for re-opening

@tkonopka
Copy link
Contributor

Hi @damianocasula, hi @Mulli. Do you mean something like this?

2022-05-28-bar-totals

https://codesandbox.io/s/hopeful-mcclintock-44m0w8?file=/src/App.js

This implementation uses a custom layer. Note the sandbox only works for vertical bar plots, but hopefully you can customize it for your needs.

@Mulli
Copy link

Mulli commented May 30, 2022 via email

@stale
Copy link

stale bot commented Sep 20, 2022

This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

@stale stale bot added the stale label Sep 20, 2022
@stale
Copy link

stale bot commented Sep 27, 2022

Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!

@stale stale bot closed this as completed Sep 27, 2022
@ChuckJonas
Copy link

Converted this solution to typescript (and did some very slight refactoring).

const BarTotalsLayer: BarLayer<{ value: number }> = ({
  bars,
  xScale,
  yScale,
}) => {
  const labelOffset = 10;
  const labelFontSize = 12;
  if (bars.length === 0) return null;
  // compute totals for each index/bar

  const totals = bars.reduce<Record<number, number>>((acc, bar) => {
    console.log(bar.data.indexValue);
    const indexValue = bar.data.indexValue;
    if (!(indexValue in acc)) {
      acc[indexValue] = 0;
    }
    if (!bar.data.hidden) {
      acc[indexValue] += bar.data.value;
    }
    return acc;
  }, {});

  const bandwidth = bars[0]?.width;
  // place text elements above the bars
  const labels = (Object.keys(totals) as any as number[]).map((indexValue) => {
    const x = xScale(indexValue) + bandwidth / 2;
    const y = yScale(totals[indexValue]) - labelOffset;
    return (
      <text
        key={'total.' + indexValue}
        x={x}
        y={y}
        textAnchor={'middle'}
        fontWeight={'bold'}
        fontSize={labelFontSize}
      >
        {totals[indexValue]}
      </text>
    );
  });
  return <>{labels}</>;
};

Note: to get the types to work, you also need to install @types/d3-scale as indicated in #2173

@joaopedromatias
Copy link
Contributor

@tkonopka thank you so muchhhh man 🚀

@elijahnikov
Copy link

For anyone having trouble doing this for the <ResponsiveBarCanvas/> component like I did trying the above solutions, you need to draw directly onto the canvas using the context provided by Nivo. This is what worked for me:

Version of Nivo I used:

"@nivo/bar": "^0.83.0",
"@nivo/core": "^0.83.0",

Import the types from @nivo/bar

import {
  ResponsiveBarCanvas,
  BarCanvasCustomLayerProps,
  BarDatum,
} from '@nivo/bar'

Add the component to the layers prop

layers={['axes', 'bars', BarTotalsLayer]}
const BarTotalsLayer = (
  context: CanvasRenderingContext2D,
  props: BarCanvasCustomLayerProps<BarDatum>
) => {
  const { bars, xScale, yScale } = props
  const labelOffset = 5
  const labelFontSize = 12
  if (bars.length === 0) return null

  const totals = bars.reduce<Record<number, number>>((acc, bar) => {
    const indexValue = bar.data.indexValue
    if (!(indexValue in acc)) {
      acc[indexValue as keyof typeof acc] = 0
    }
    if (!bar.data.hidden) {
      acc[indexValue as keyof typeof acc] += bar.data.value!
    }
    return acc
  }, {})

  const bandwidth = bars[0]?.width

  return (Object.keys(totals) as any as number[]).forEach((indexValue) => {
    const x = xScale(indexValue) + bandwidth / 2
    const y = yScale(totals[indexValue]) - labelOffset

    context.font = `600 ${labelFontSize}px 'IBM Plex Sans', sans-serif`
    context.fillStyle = '#575756'
    context.textAlign = 'center'
    context.fillText(`${totals[indexValue]}`, x, y - labelOffset)
  })
}

Of course adjust the styling how you desire

@plouc
Copy link
Owner

plouc commented Mar 19, 2024

Implemented in #2525 thanks to @joaopedromatias.

@plouc plouc closed this as completed Mar 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

6 participants