如何在 recharts 的 y 轴上显示数据的标签名称?

How to show label name of a data in y-axis in recharts?

问题:

我使用 recharts 创建了一个垂直条形图。我在这里提供我的代码。

import React, { Component, PureComponent } from "react";

import { Card, CardBody, CardTitle } from "reactstrap";
import {
  Bar,
  BarChart,
  Tooltip,
  XAxis,
  YAxis,
  ResponsiveContainer,
  Cell,
  LabelList
} from "recharts";

import "./SubcribersByRegion.css";

const colors = [
  "#138185",
  "#26a0a7",
  "#65d3da",
  "#79d69f",
  "#cbe989",
  "#ebf898",
  "#f9ec86",
  "#fad144",
  "#ec983d",
  "#d76c6c"
];

const data = [
  {
    name: "Page A",
    pv: 2400,
    amt: 2400
  },
  {
    name: "Page B",
    pv: 1398,
    amt: 2210
  },
  {
    name: "Page C",
    pv: 9800,
    amt: 2290
  },
  {
    name: "Page D",
    pv: 3908,
    amt: 2000
  },
  {
    name: "Page E",
    pv: 4800,
    amt: 2181
  },
  {
    name: "Page F",
    pv: 3800,
    amt: 2500
  },
  {
    name: "Page G",
    pv: 4300,
    amt: 2100
  },
  {
    name: "Page H",
    pv: 4300,
    amt: 2100
  },
  {
    name: "Page I",
    pv: 4300,
    amt: 2100
  },
  {
    name: "Page J",
    pv: 4300,
    amt: 2100
  }
];

class SubcribersByRegion extends Component {
  render() {
    return (
      <div>
        <Card className="subscribers-by-region-card">
          <CardTitle className="subscribers-by-region-card-title">
            Subscribers by Region
          </CardTitle>
          <CardBody>
            <ResponsiveContainer width="100%" height="100%" aspect={5.0 / 6.0}>
              <BarChart
                data={data}
                layout="vertical"
                barGap={4}
                margin={{
                  top: 6,
                  right: 50,
                  left: 0,
                  bottom: 0
                }}
              >
                <Tooltip />
                <XAxis type="number" className="xaxies" dy={1} />
                <YAxis type="category" />
                <Bar dataKey="pv" fill="#8884d8" maxBarSize={10}>
                  {data.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={colors[index]} />
                  ))}
                  <LabelList dataKey="pv" position="right" />
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </CardBody>
        </Card>
      </div>
    );
  }
}

export default SubcribersByRegion;

这在 y 轴上显示 0,1,2....... 我想显示页面 A、页面 B... 有人可以通过修改我的代码来帮助我解决这个问题吗?谢谢?我尝试了很多方法来找到解决这个问题的方法,但是我找不到任何好的解决方法来解决这个问题。

您只需指定轴的 dataKey 是什么。

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

https://recharts.org/en-US/api/YAxis

从文档中,我们可以看到 <Label />YAxis

的子组件

https://recharts.org/en-US/api/Label

Labelvalue

的道具

添加 Label 组件作为 YAxis

的子组件

添加样式https://github.com/recharts/recharts/issues/720

<YAxis dataKey={"height"} yAxisId={"height"}>
    <Label
         style={{
             textAnchor: "middle",
             fontSize: "130%",
             fill: "white",
         }}
      angle={270} 
      value={"Height (ft.)"} />
</YAxis>