개발

Chart.js Realtime 적용하기

devskim 2023. 4. 24. 02:19

1. 패키지 설치

  • 호환성 문제로 다음에 지정된 버전의 라이브러리를 설치한다.
npm install chart.js@^3.9.1 react-chartjs-2@^4.3.1 luxon chartjs-adapter-luxon chartjs-plugin-streaming --save

 

 

2. 코드 작성

  • Chart.register 를 통해서 필요한 변수는 모두 불러와야 한다.
  • 아래 코드에서는 data에 빈 배열을 넣고, onRefresh 함수 내에서 데이터를 추가해주었다.
    • 이와 달리 state 값을 따로 할당하고, 특정 이벤트에 해당 값을 변경하도록 개발해도 괜찮다.
import {
    CategoryScale,
    Chart,
    Legend,
    LinearScale,
    LineElement,
    PointElement,
    Title,
    Tooltip,
} from 'chart.js';
import { RealTimeScale, StreamingPlugin } from 'chartjs-plugin-streaming';
import React from 'react';
import { Line } from 'react-chartjs-2';
import 'chartjs-adapter-luxon';

Chart.register(
    StreamingPlugin,
    RealTimeScale,
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend
);

function ChartExample() {
    return (
    <Line
        data={{
        datasets: [
            {
            label: 'Dataset 1',
            backgroundColor: 'rgba(255, 99, 132, 0.5)',
            borderColor: 'rgb(255, 99, 132)',
            borderDash: [8, 4],
            fill: true,
            data: [],
            },
            {
            label: 'Dataset 2',
            backgroundColor: 'rgba(54, 162, 235, 0.5)',
            borderColor: 'rgb(54, 162, 235)',
            cubicInterpolationMode: 'monotone',
            fill: true,
            data: [],
            },
        ],
        }}
        options={{
        scales: {
            x: {
            type: 'realtime',
            realtime: {
                delay: 2000,
                onRefresh: (chart) => {
                chart.data.datasets.forEach((dataset) => {
                    dataset.data.push({
                    x: Date.now(),
                    y: Math.random(),
                    });
                });
                },
            },
            },
        },
        }}
    />
    );
}

export default ChartExample;

 

 

3. 결과물