Development/Chart.js
Chart.js - chartjs-plugin-datalabels
레오나르도 다빈츠
2022. 8. 20. 13:57
Chart.js에서 기본적으로 제공하는 데이터 레이블이 구현하는데 한계가 있어 이 플러그인을 사용했다.
chartjs-plugin-datalabels
chartjs-plugin-datalabels.netlify.app
◽ Scriptable
옵션은 스크립팅이 가능한 경우도 있고 아닌 경우도 있어서 문서를 확인해보면 된다.
Scriptable 항목이 'Yes'이면 동적으로 옵션을 줄 수도 있다.
(하지만.. 문서에 스크립트를 사용할 수 없다고 작성되어 있었음에도 동작하는 것들이 있었다.)
◽ Option
const dataLabelOption = {
offset: 0, // 레이블의 패딩 적용 (기본값이 4이기 때문에 0으로 조정)
borderRadius: '5', // 레이블을 감싸는 영역에 border-radius 적용
clamp: true, // 데이터레이블이 차트 영역밖으로 나가지 않도록 조정
// display: 데이터레이블 노출여부
display: function (context: any) {
if (!isShowDatalabel) {
return false
} else {
return true
}
},
// backgroundColor: 배경색
backgroundColor: function (ctx: any) {
const value = ctx.dataset.data[ctx.dataIndex]
if ([분기조건]) {
return '#ffffff'
} else {
return '#050c24b3'
}
},
// color: 폰트 색상
color: function (ctx: any) {
const value = ctx.dataset.data[ctx.dataIndex]
if ([분기조건]) {
return '#ffffff'
} else {
return color
}
},
// font: 폰트
font: {
size: 13,
weight: 'bold',
family: ['NanumSquare', 'FontAwesome'],
},
// padding: 패딩
padding: {
top: 3,
bottom: 2,
left: 5,
right: 5,
},
// formatter: 값 포맷 변경
formatter: function (value: any, context: any) {
if ([분기조건]) {
const icon = getIconUnicode([파라미터]) // 해당 아이콘의 unicode를 가져오는 함수
// FontAwesome 사용
return value ? `${icon.unicode} ${adjustFormat(value)}` : value
} else {
return value ? `${adjustFormat(value)}` : value
}
},
// anchor: 데이터레이블의 위치 조정 1
anchor: (context: any) => {
const anchor = []
const idx = context.dataset.data[context.dataIndex]
if (idx >= 0) {
anchor.push('end')
} else {
anchor.push('start')
}
return anchor
},
// align: 데이터레이블의 위치 조정 2
align: (context: any) => {
const anchor = []
const idx = context.dataset.data[context.dataIndex]
if (idx >= 0) {
anchor.push('top')
} else {
anchor.push('bottom')
}
return anchor
},
}
개인적으로 공부한 내용을 정리하는 블로그로
잘못된 개념을 게시하지않도록 주의하고 있으나 오류가 있을 수 있습니다.