2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactでグラフを表示するために使う Recharts(リチャーツ)

2
Posted at

Rechartsって何?

Reactで簡単にグラフが作れるライブラリです。
棒グラフ・円グラフ・折れ線グラフなどが用意されていて、コンポーネントを書くだけで表示できます!

円グラフを表示してみよう!

1.まずはライブラリのインストール

 npm install recharts

2.必要なものをインポートする

import { PieChart, Pie, Legend, Tooltip, Cell } from 'recharts'

実際に使うファイル(ディレクトリ)にこのインポート文を書く

何をimportしてるの?

名前 役割
PieChart 円グラフ全体を囲むコンポーネント
Pie 円グラフのデータ部分
Cell 円グラフの各ピースに色をつける
Legend 凡例(何色が何を表すか)を表示する
Tooltip グラフにマウスを乗せたとき数値を表示する

3.Rechartsに渡すデータを作る

Recharts{ name: 表示名, value: 数値 } という形のオブジェクトの配列を渡すと理解してくれます!
これはRechartsのルールなので覚えておくと便利です

const chartData = [
  { name: '収入', value: totalIncome },
  { name: '支出', value: totalExpense },
]

4.グラフを画面に表示する部分を追加

<div className="mt-4">
        <h5>収支グラフ</h5>
        <PieChart width={400} height={400}>//グラフのサイズ設定
          <Pie
            data={chartData}//さっき作ったデータを渡す
            dataKey="value"//数値として使う項目名(Rechartsのルール)
            nameKey="name"//表示名として使う項目名(Rechartsのルール)
            cx="50%"//グラフを中央に配置する
            cy="50%"//グラフを中央に配置する
            outerRadius={150}//円グラフの半径
          >
            <Cell fill="#28a745" />//ここで好きな色に変えれる
            <Cell fill="#dc3545" />
          </Pie>
          <Legend />//凡例を表示する
          <Tooltip />//マウスを乗せたとき数値を表示する
        </PieChart>
      </div>

そしたらこんな感じで表示されるようになります!
image.png

棒グラフを表示してみよう!

※ライブラリーのインストールやデータを渡すところは円グラフの方でやったので省略します。

1.必要なものをインポートする

import {BarChart, Bar, XAxis, YAxis, CartesianGrid } from 'recharts'
名前 役割
BarChart 棒グラフ全体を囲むコンポーネント
Bar 棒グラフの棒の部分
XAxis 横軸
YAxis 縦軸
CartesianGrid グラフの背景の格子線

2.グラフを画面に表示する部分を追加

<div className="mt-4">
  <h5>収支棒グラフ</h5>
  <BarChart width={400} height={300} data={chartData}>//円グラフと同じデータを使う
    <CartesianGrid strokeDasharray="3 3" />//背景に点線のグリッドを表示する
    <XAxis dataKey="name" />//横軸に name(収入・支出)を表示する
    <YAxis />//縦軸に金額を表示する
    <Tooltip />
    <Legend />
    <Bar dataKey="value" fill="#8884d8" />//value(金額)を棒グラフで表示する。色は紫
  </BarChart>
</div>

そうすると
image.png

こんな感じで表示されるようになります!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?