bar-chartrecharts

Recharts - Horizontal bar chart


I have this vertical barchart working normally. enter image description here

const data = [
  { name: "Yes", value: 35 },
  { name: "Not sure", value: 21 },
  { name: "No", value: 13 },
];
    <ResponsiveContainer
      width={"100%"}
      height={"100%"}
    >
      <BarChart
        layout="horizontal"
        data={data}
        margin={{
          top: 20,
          right: 20,
          bottom: 20,
          left: 20,
        }}
      >
        <XAxis dataKey={"name"} />
        <YAxis dataKey="value" />
        <Bar dataKey="value" fill="#413ea0" />
      </BarChart>
    </ResponsiveContainer>

However, when changing the layout and the datakey values, the info is not getting displayed properly:

enter image description here

    <ResponsiveContainer
      width={"100%"}
      height={"100%"}
    >
      <BarChart
        layout="vertical"
        data={data}
        margin={{
          top: 20,
          right: 20,
          bottom: 20,
          left: 20,
        }}
      >
        <XAxis dataKey={"value"} />
        <YAxis dataKey="name" />
        <Bar dataKey="value" fill="#413ea0" />
      </BarChart>
    </ResponsiveContainer>

I tried reading the documentation


Solution

  • The recharts API defaults XAxis to type="category" and YAxis to type="number", so when you swap default layout you'll also need to swap which axis is which type.

    In this case:

    <XAxis type="number" />
    <YAxis dataKey="name" type="category" />
    

    Here is a sandbox that demonstrates what you would need to toggle between the two.

    https://codesandbox.io/p/sandbox/simple-bar-chart-toggle-layout-tkjczm