📅  最后修改于: 2023-12-03 15:23:18.444000             🧑  作者: Mango
Recharts 是一个 ReactJS 的图表库,支持多种类型的图表,包括折线图,柱状图,饼图和环形图等。本文将介绍如何在 ReactJS 中使用 Recharts 创建环形图。
使用 npm 安装:
npm install recharts
首先,需要导入 Recharts 组件:
import { ResponsiveContainer, PieChart, Pie, Cell, Tooltip } from 'recharts';
然后,可以创建环形图的组件:
const data = [
{ name: 'A', value: 200 },
{ name: 'B', value: 100 },
{ name: 'C', value: 300 },
];
const COLORS = ['#0088FE', '#00C49F', '#FFBB28'];
const RADIAN = Math.PI / 180;
const renderCustomizedLabel = ({
cx,
cy,
midAngle,
innerRadius,
outerRadius,
percent,
index,
}) => {
const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
const x = cx + radius * Math.cos(-midAngle * RADIAN);
const y = cy + radius * Math.sin(-midAngle * RADIAN);
return (
<text
x={x}
y={y}
fill="white"
textAnchor="middle"
dominantBaseline="central"
>
{`${data[index].name} ${percent.toFixed(0)}%`}
</text>
);
};
const PieChartComponent = () => {
return (
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={data}
cx="50%"
cy="50%"
labelLine={false}
label={renderCustomizedLabel}
outerRadius={80}
fill="#8884d8"
dataKey="value"
>
{data.map((entry, index) => (
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
))}
</Pie>
<Tooltip />
</PieChart>
</ResponsiveContainer>
);
};
数据源,需要一个数组类型,其中包含每个类别的名称和值。
颜色集合,用于绘制每个类别的扇形,深色的颜色表示每个不同的类别。
用于计算弧度的角度。
这个函数用于自定义每个扇形中的文本,需要返回一个 React 元素。
ResponsiveContainer 允许图表根据其容器的尺寸进行调整,可根据需要设置宽度和高度。
PieChart 是环形图的根元素,其中可以包含多个扇形。
Pie 是每个扇形的元素,其中需要设置数据源和需要的参数,如颜色、内外半径等。
每个 Cell 对应每个类别,它需要一个特定的颜色。
Tooltip 用于显示鼠标悬停在扇形上的提示信息,包含类别名称和值。
通过 Recharts,我们可以很容易地在 ReactJS 中创建环形图。使用上文提到的参数可以自定义图表的样式和效果,非常方便。