如何在 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 的值。您會注意到結果類似於以下內容:
廣告