tremorlabs / tremor

React components to build charts and dashboards
https://tremor.so
Apache License 2.0
15.39k stars 446 forks source link

[Feature]: BarChart - Allow `stackId` to be specified for "mixed" bar charts #997

Open BenJenkinson opened 1 month ago

BenJenkinson commented 1 month ago

What problem does this feature solve?

I want to display a "mixed" bar chart; where some bars within a category are stacked and others are either not, or are stacked separately.

image

This is possible in recharts, the library that tremor is using to display charts, using the stackId property:

In tremor, this line currently sets all bars to use the same stack:

https://github.com/tremorlabs/tremor/blob/bd6566b814d907e130b6827194def10b5bc3661f/src/components/chart-elements/BarChart/BarChart.tsx#L335

What does the proposed API look like?

Suggestion 1

With this addition, there are really several different props taken by tremor related to categories, that are passed to the recharts <Bar> component.

You could consider changing the categories prop from string[] to some kind of Category[] object:

const data = [
  {
    name: "House #1",
    "2022-water": 50,
    "2022-electricity": 100,
    "2023-water": 65,
    "2023-electricity": 140,
  },
  {
    name: "House #2",
    "2022-water": 30,
    "2022-electricity": 100,
    "2023-water": 15,
    "2023-electricity": 85,
  },
];

export default function Example() {
  return (
    <BarChart
      data={data}
      categories={[
        { dataKey: "2022-water", color: "blue", stackId: "2022" },
        { dataKey: "2022-electricity", color: "yellow", stackId: "2023" },
        { dataKey: "2023-water", color: "blue", stackId: "2022" },
        { dataKey: "2023-electricity", color: "yellow", stackId: "2023" },
      ]}
    />
  );
}

Suggestion 2

To avoid changing the type of the categories prop to be some kind of Category[] rather than string[], you could copy the pattern followed by the categories and colors props:

const data = [
  {
    name: "House #1",
    "2022-water": 50,
    "2022-electricity": 100,
    "2023-water": 65,
    "2023-electricity": 140,
  },
  {
    name: "House #2",
    "2022-water": 30,
    "2022-electricity": 100,
    "2023-water": 15,
    "2023-electricity": 85,
  },
];

export default function Example() {
  return (
    <BarChart
      data={data}
      categories={[
        "2022-water",
        "2022-electricity",
        "2023-water",
        "2023-electricity",
      ]}
      colors={["blue", "yellow", "blue", "yellow"]}
      stacks={["2022", "2022", "2023", "2023"]}
    />
  );
}