Skip to content
Advertisement

Error in the values of the Rechart Stacked chart

I’m trying to build a Stacked Bar Chart using the Pchart library. I attach the code below.

function StackedBarChart({...props}){
    const {dataChart:{data,keys}} = props;

    const renderBars = () =>{
        return keys.map((item,index)=>(
            <Bar
                key={index}
                dataKey={item}
                stackId='a'
                fill={index%2?'blue':'red'}
                label
            />
        ))
    }

    return(
        <ResponsiveContainer width='100%' height={400}>
            <BarChart
                data={data}
                stackOffset='expand'
                >
                <XAxis dataKey="name" />
                <YAxis />
                {renderBars()}
            </BarChart>
        </ResponsiveContainer>
    )
}

When I output a value to each Bar I get incorrect signatures.enter image description here . Why is 2 Bar subscribed with the value 1 and not the remaining percentage. What is my mistake ?

my data

const dataChart = {
  data: [{
      name: 'Page A',
      count: 4000,
      price: 2400,
    },
    {
      name: 'Page B',
      count: 3000,
      price: 1398,
    },
    {
      name: 'Page C',
      count: 2000,
      price: 9800,
    },

  ],
  keys: ['price', 'count']
};

Advertisement

Answer

The reason of this behavior, is that upper bar shown his top value, which is 1, so this is the sum of all bars stacked.

To avoid this situation I used valueAccessor and some formatting to get value of bar and count its percentage.

Here is a link to working codesandbox where you can see final result

Advertisement