如何在 ReactJS 中使用 Recharts 创建面积图?
在本文中,我们将探索 **Rechart JS** 库,并将其在 React 应用中实现,以了解其使用方法。Rechart 库专门用于在 React 应用中创建各种类型的图表。可以使用此库构建的图表包括折线图、条形图、饼图、面积图等。
在本教程中,我们将使用所需的数据点创建一个 **面积图**,并将其显示给用户。我们将使用数据属性(由数据集中的数据定义)来定义面积图的切片。data-key 属性是具有切片值的属性名称。
创建 React 应用
1. 使用以下命令创建一个简单的 React 应用:
npx create-react-app myApp
2. 应用创建后,转到其应用文件夹。
cd myApp
3. 现在,使用以下命令安装要在 ReactJS 应用中使用的 recharts 模块。
npm install --save recharts
添加库后,我们可以使用此库创建饼图。
示例 1
在下面的示例中,我们使用 Recharts 依赖项创建了一个面积图。请将以下代码添加到您的 app.js 文件中,以在您的 React 应用中配置面积图。
# app.js
import React from "react";
import {
AreaChart,
Area,
YAxis,
XAxis,
CartesianGrid,
Tooltip,
Legend
} from "recharts";
class AreaRechartComponent extends React.Component {
data = [
{
name: "Jan 2019",
"Product A": 3432,
"Procuct B": 2342
},
{
name: "Feb 2019",
"Product A": 2342,
"Procuct B": 7746
},
{
name: "Mar 2019",
"Product A": 4565,
"Procuct B": 2556
},
{
name: "Apr 2019",
"Product A": 6654,
"Procuct B": 4465
},
{
name: "May 2019",
"Product A": 8765,
"Procuct B": 5553
}
];
render() {
return (
<AreaChart
width={730}
height={250}
data={this.data}
margin={{ top: 10, right: 30, left: 0, bottom: 0 }}>
<defs>
<linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#8884d8" stopOpacity={0.8} />
<stop offset="95%" stopColor="#8884d8" stopOpacity={0} />
</linearGradient>
<linearGradient id="colorPv" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#82ca9d" stopOpacity={0.8} />
<stop offset="95%" stopColor="#82ca9d" stopOpacity={0} />
</linearGradient>
</defs>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Area
type="monotone"
dataKey="Product A"
stroke="#8884d8"
fillOpacity={1}
fill="url(#colorUv)"/>
<Area
type="monotone"
dataKey="Procuct B"
stroke="#82ca9d"
fillOpacity={1}
fill="url(#colorPv)"/>
</AreaChart>
);
}
}
export default AreaRechartComponent;输出
以上程序生成了从 2019 年 1 月到 2019 年 5 月的产品 A 和产品 B 的面积图。当您将鼠标悬停在图表上时,它会显示产品 A 和产品 B 的值。您会注意到结果类似于以下内容:

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP