그 땐 IT활동했지/그 땐 영일영 근무했지

[010/JS Library] chart.js | 그래프 커스텀하기 (함수편)

루이란 2022. 3. 24. 19:11
728x90

문제 상황

2022.03.23 - [그 땐 IT활동했지/그 땐 영일영 근무했지] - [010/API] chart.js | 그래프 커스텀하기 (일반편)

차트 커스텀은 여차저차 해냈다! 커스섬 방법과 상세코드가 궁금하면 위의 이전 포스팅을 보자!

하지만! 커스텀도 조건부로 하고 싶다면? 그 때 함수를 사용하면 된다! 함수 사용법을 알아보자!

 

오늘도 공식문서 참고 :)

https://www.chartjs.org/docs/latest/

 

Chart.js | Chart.js

Chart.js (opens new window) Installation You can get the latest version of Chart.js from npm (opens new window), the GitHub releases (opens new window), or use a Chart.js CDN (opens new window). Detailed installation instructions can be found on the instal

www.chartjs.org

https://chartjs-plugin-datalabels.netlify.app/

 

chartjs-plugin-datalabels

 

chartjs-plugin-datalabels.netlify.app

데이터 레이블 위치
options: {
    plugins: {
        datalabels: {
            color: 'black',
            anchor: 'end',
            clamp: true,
            clip: true,
            align: '-135',
            offset: 1,
            formatter: function (value, context){
                let result = value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                return result + '원'
            },
            display: function(context) {
                if ( context.dataIndex === lastDataIndex ) { 
                	return 1 
                }
                else { 
                	return 0 
                }
            }
        },
    },
}

1️⃣formatter

👉🏻데이터레이블 값을 어떤 형식으로 표시할지 설정한다. 나의 경우 천의자리 단위로 콤마가 붙어야 하고 가격 뒤에 '원'이 붙어야 하기 때문에 함수를 사용했다!

formatter: function (value, context){
    let result = value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    return result + '원'
},

👉🏻여기서 value는 데이터레이블 자체이다. 들어온 데이터레이블을 입맛대로 처리해주면 된다.

✍🏻정규표현식을 통해 천의 자리에 콤마를 찍어주고 '원'을 붙어 반환했다.

formatter 설정 전후

2️⃣display

👉🏻데이터레이블의 표시여부를 설정한다. 나의 경우 맨 마지막 값만 출력하도록 만들어야했다.

let lastDataIndex = chartData.datasets[0].data.length - 1;

...

display: function(context) {
    if ( context.dataIndex === lastDataIndex ) { 
        return 1 
    }
    else { 
        return 0 
    }
}

👉🏻여기서 context가 뭔지 궁금해 출력해보니 아래와 같이 나왔다. 

👉🏻데이터레이블 하나하나가 가진 차트의 속성이 object로 묶인 것 같다. 내가 초록 동그라미로 친 dataIndex에 데이터레이블의 Index값이 담겨있기 때문에 이걸 이용했다!

✍🏻이전에 lastDataIndex라는 변수에 데이터레이블의 마지막 Index를 정의한 적이 있다. 때문에 이걸 이용해 마지막인 데이터레이블만 출력했다. 이 때 1을 출력했는데 1은 'true'를 의미하므로 결과적으로 'display: true'가 되는 것이다.

display 설정 전후

x축과 y축
options: {
    scales: {
            y: {
                type: 'linear',
                position: 'right',
                grace: '5%',
                grid: {
                    display: false,
                },
            },
            x: {
                grid: {
                    display: false,
                },
                ticks: {
                    color: function (ctx) {
                        if ( ctx.index === lastDataIndex ) { 
                        	return '#426AE6' 
                        }
                        else { 
                        	return 'black' 
                        }
                    }
                }
            },
        }
    },
}

1️⃣ticks - color

👉🏻x축의 값의 색을 표시해준다. 나는 마지막 값만 파란색으로 출력해야하는 조건 때문에 함수를 사용했다.

color: function (ctx) {
    if ( ctx.index === lastDataIndex ) { 
        return '#426AE6' 
    }
    else { 
        return 'black' 
    }
}

👉🏻인덱스가 마지막 인덱스일 때 파란색을 반환했다.

color 설정 전
color 설정 후

728x90