reactjsrecharts

How to create a different colors per bar stack in ReChart


I am attempting to create a Stacked BarChart with diffrent fill colors below is my code so far, based on some answers here i can access the data array using data[0].color, so i tried to map the data array but did not work for me.

Is there a way to render the Bar individually using reCharts i was thinking of just create a static value for each bar value but its not a scalable approach.

import { BarChart, CartesianGrid, XAxis, YAxis, Tooltip, Bar } from "recharts";

const BarChartComponent = () => {
  const data = [
    {
      name: "Skill",
      Before: 4000,
      After: 2400,
      color1: "#53A9DA",
      color: "#BADDF0",
    },
    {
      name: "Role",
      Before: 3000,
      After: 1398,
      color1: "#DFD3F9",
      color: "#AF91F0",
    },
    {
      name: "Missions",
      Before: 2000,
      After: 9800,
      color1: "#FADCAF",
      color: "#F2A838",
    },
    {
      name: "Guild",
      Before: 2780,
      After: 3908,
      color1: "#CCEEB2",
      color: "#7FD33F",
    },
  ];
  return (
    <BarChart
      layout="vertical"
      width={600}
      height={400}
      data={data}
      margin={{
        top: 30,
        right: 5,
        bottom: 20,
        left: 50,
      }}
    >
      <CartesianGrid stroke="#f5f5f5" />
      <XAxis type="number" />
      <YAxis dataKey="name" type="category" />
      <Tooltip />

      <>
        <Bar dataKey="After" stackId="a" fill={data[0].color1} />
        <Bar dataKey="Before" stackId="a" fill={data[0].color} />
      </>
    </BarChart>
  );
};

export default BarChartComponent;

Solution

  • The Recharts documentation has something relevant here:

    https://recharts.org/en-US/examples/CustomShapeBarChart

    Namely, using the <Cell/> internal component of the bar, with its fill dynamically mapped from iterating over your data array.

    I've put together a quick CodeSandbox demonstrating the approach:

    https://codesandbox.io/s/stupefied-wildflower-p2dvr8?file=/src/App.tsx

    Namely:

    <Bar dataKey="After" stackId="a">
       {data.map((entry, index) => (
         <Cell key={`cell-${index}`} fill={entry.color1} />
       ))}
    </Bar>