javascript 如何使用Recharts创建垂直堆叠条形图?

bfrts1fy  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(101)

我试图简单地交换x轴的y轴上的条形图使用recharts。
然而,当我试图将布局从水平条切换到垂直条时,我的图表变得不稳定,不是我想要的布局。
我想要的图表由4个互相堆叠的条形图组成。y轴是条形图的名称,x轴是条形图的值。
下面是我的代码和一个codesandbox链接:

codesandboxhttps://codesandbox.io/s/simple-bar-chart-forked-6ksutx?file=/src/App.tsx:176-180

import "./styles.css";
import React from "react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend
} from "recharts";

const data = [
  {
    name: "A",
    value: 5
  },
  {
    name: "B",
    value: 10
  },
  {
    name: "C",
    value: 15
  },
  {
    name: "D",
    value: 20
  }
];

export default function App() {
  return (
    <BarChart width={500} height={300} data={data} layout="vertical">
      <XAxis dataKey="name" type="category" />
      <YAxis dataKey="value" type="number" />
      <Bar dataKey="name" fill="#8884d8" />
      <Tooltip/>
    </BarChart>
  );
}
c8ib6hqw

c8ib6hqw1#

将XAxis类型设置为number对我来说很有用,下面的例子是如何在BarChart(Stack)上实现它

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

const BarChartComponent = () => {
  const data = [
    {
      name: "Page A",
      uv: 4000,
      pv: 2400,
      amt: 2400,
    },
    {
      name: "Page B",
      uv: 3000,
      pv: 1398,
      amt: 2210,
    },
    {
      name: "Page C",
      uv: 2000,
      pv: 9800,
      amt: 2290,
    },
    {
      name: "Page D",
      uv: 2780,
      pv: 3908,
      amt: 2000,
    },
    {
      name: "Page E",
      uv: 1890,
      pv: 4800,
      amt: 2181,
    },
    {
      name: "Page F",
      uv: 2390,
      pv: 3800,
      amt: 2500,
    },
    {
      name: "Page G",
      uv: 3490,
      pv: 4300,
      amt: 2100,
    },
  ];
  return (
    <BarChart
      layout="vertical"
      width={500}
      height={500}
      data={data}
      margin={{
        top: 30,
        right: 20,
        bottom: 10,
        left: 10,
      }}
    >
      <CartesianGrid stroke="#f5f5f5" />
      <XAxis type="number" />
      <YAxis dataKey="name" type="category" />
      <Tooltip />
      <Legend />
      <Bar dataKey="pv" stackId="a" fill="#8884d8" />
      <Bar dataKey="uv" stackId="a" fill="#82ca9d" />
    </BarChart>
  );
};

export default BarChartComponent;

相关问题