LoginSignup
4
0

More than 1 year has passed since last update.

TypeScript環境でChart.js v4を使いたい

Last updated at Posted at 2022-12-10

はじめに

業務中に学んだことをアウトプットするために簡単にまとめてみます。

やりかた

公式サイトで最新バージョンを確認するとv4でした。
前のバージョンとimportの書き方などが異なるようなので他サイトの記事を参考にする際は気を付けた方が良いです。

導入

公式サイトではnpm install chart.jsと記載されています

Reactで使用したいので今回はreact-chartjs-2が必要なのと、yarnで導入するので以下を実行します

yarn add -D chart.js react-chartjs-2

実行サンプル

image.png

以下のWeight.tsxをApp.tsxで呼び出します

Weight.tsx
import React from "react";
import { Line } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);
const Scale = {
  y: {
    min: 0,
    max: 100,
    title: {
      display: true,
      text: "weight",
      color: "#FF4500",
      rotate: "vertical",
      font: {
        size: 20,
      },
    },
    ticks: {
      stepSize: 10,
    },
  },
  x: {
    title: {
      display: true,
      text: "month",
      color: "rgb(255,69,0)",
      font: {
        size: 20,
      },
    },
  },
};

export const options = {
  responsive: true,
  plugins: {
    legend: {
      position: "top" as const,
    },
    title: {
      display: true,
      text: "graph",
    },
  },
  scales: Scale,
};

const labels = ["January", "February", "March"];
const data = {
  labels,
  datasets: [
    {
      label: "Aさん",
      data: [55, 50, 60],
      borderColor: "rgb(255, 99, 132)",
      backgroundColor: "yellow",
    },
  ],
};

export const Weight = () => {
  return <Line options={options} data={data} />;
};

おわりに

グラフ描画系ができるようになると分析系のシステム開発に利用できるのでこれからも学んでいきたいです。

4
0
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
4
0