使用 ReactJS 中的 Recharts 建立散點圖
在本文中,我們將探索 **Rechart JS** 庫並在 React 應用程式中實現它,以瞭解其使用方法。Rechart 庫專門用於在 React 應用程式上建立不同型別的圖表。可以使用此庫構建的圖表包括折線圖、條形圖、餅圖、散點圖等。
在本教程中,我們將使用所需的資料點建立一個 **散點圖** 並將其顯示給使用者。散點圖的資料集將具有 x 和 y 座標詳細資訊。然後,藉助笛卡爾積,我們將在這兩條軸上建立一個網格。最後,散點將繪製在笛卡爾網格上。
建立 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 { ScatterChart, Scatter, XAxis, YAxis, CartesianGrid, Tooltip } from "recharts"; const data01 = [ { x: 100, y: 60, z: 200 }, { x: 120, y: 30, z: 260 }, { x: 170, y: 50, z: 400 }, { x: 140, y: 55, z: 280 }, { x: 150, y: 70, z: 500 }, { x: 110, y: 58, z: 200 } ]; const data02 = [ { x: 300, y: 300, z: 200 }, { x: 400, y: 500, z: 260 }, { x: 200, y: 700, z: 400 }, { x: 340, y: 350, z: 280 }, { x: 560, y: 500, z: 500 }, { x: 230, y: 780, z: 200 }, { x: 500, y: 400, z: 200 }, { x: 300, y: 500, z: 260 }, { x: 240, y: 300, z: 400 }, { x: 320, y: 550, z: 280 }, { x: 500, y: 400, z: 500 }, { x: 420, y: 280, z: 200 } ]; export default class Example extends React.Component { render() { return ( <ScatterChart width={500} height={400} margin={{ top: 20, right: 20, bottom: 20, left: 20 }} > <CartesianGrid /> <XAxis type="number" dataKey="x" name="height" unit="cm" /> <YAxis yAxisId="left" type="number" dataKey="y" name="weight" unit="kg" stroke="#8884d8"/> <YAxis yAxisId="right" type="number" dataKey="y" name="weight" unit="kg" orientation="right" stroke="#82ca9d"/> <Tooltip cursor={{ strokeDasharray: "3 3" }} /> <Scatter yAxisId="left" name="A school" data={data01} fill="#8884d8" /> <Scatter yAxisId="right" name="A school" data={data02} fill="#82ca9d" /> </ScatterChart> ); } }
輸出
成功執行上述程式後,它將生成一個散點圖。當您將滑鼠懸停在這些點上時,它會顯示高度(以釐米為單位)和體重(以公斤為單位)。
廣告