Search code examples
bar-chartrechartsstacked-bar-chart

is it possible to stack 2 bars, layer on top of each other (not above each other)?


Trying to build a bar chart where each bar is essentially 2 bars layered on top of each other, and the top-most bar will be thinner than the bottom bar.

I see the existing feature where if you provide a "stackId", it stacks it, but it is stacked above it, which isn't what I want.

I've been trying to customize a bar shape that supports this, but failing to do so.

What makes this more tricky is, we're using log scaling for the Y axis.

Any input on this would greatly be appreciated!

EDIT: Attaching a mock of what I'm trying to do:

layered bar chart

1


Solution

  • Great question. That certainly is possible. While rendering multiple Bar elements, they will be put on a single axis next to each other.

    The trick is to use multiple x-axes. To show how this works, I added a new story to the Recharts storybook.

    You can find the code for it in this PR and soon in the repo itself. For the sake of a complete answer, I am duplicating the code here.

          <ResponsiveContainer width="100%" height={400}>
            <BarChart data={data}>
              <Bar dataKey="uv" fill="green" xAxisId="one" barSize={50} />
              <XAxis xAxisId="one" />
              {/* The smaller bar must be rendered in front of the larger one to be visible. */}
              <Bar dataKey="pv" fill="red" xAxisId="two" barSize={30} />
              <XAxis xAxisId="two" hide />
            </BarChart>
          </ResponsiveContainer>
    

    enter image description here