레슨 3 / 8·20분
차트 커스터마이징
options 객체 구조
Chart.js의 options 객체를 통해 차트의 거의 모든 시각 요소를 커스터마이징할 수 있습니다. 반응형 설정, 플러그인(범례, 제목, 툴팁), 축(scales) 설정 등을 자유롭게 조합합니다.
javascript
const chart = new Chart(ctx, {
type: 'bar',
data: { /* ... */ },
options: {
responsive: true, // 화면 크기에 맞게 자동 조절
maintainAspectRatio: false, // 종횡비 고정 해제
plugins: {
legend: {
display: true,
position: 'top', // 'top' | 'bottom' | 'left' | 'right'
labels: {
font: { size: 14 },
color: '#333',
},
},
title: {
display: true,
text: '월별 매출 현황',
font: { size: 18, weight: 'bold' },
padding: { bottom: 20 },
},
tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0.8)',
titleFont: { size: 14 },
bodyFont: { size: 12 },
callbacks: {
label: (context) =>
context.dataset.label + ": " + context.parsed.y.toLocaleString() + "만원",
},
},
},
},
});축(Scales) 커스터마이징
scales 옵션으로 X축과 Y축의 범위, 눈금 간격, 레이블 서식 등을 세밀하게 제어할 수 있습니다.
javascript
options: {
scales: {
x: {
title: {
display: true,
text: '월',
font: { size: 14 },
},
grid: {
display: false, // X축 그리드 라인 숨기기
},
},
y: {
beginAtZero: true, // Y축 0부터 시작
max: 500,
title: {
display: true,
text: '매출 (만원)',
},
ticks: {
stepSize: 50, // 눈금 간격
callback: (value) => value.toLocaleString() + '만원',
},
},
},
}애니메이션과 이벤트
javascript
options: {
animation: {
duration: 1500, // 애니메이션 시간 (ms)
easing: 'easeOutBounce', // 이징 함수
},
onClick: (event, elements) => {
if (elements.length > 0) {
const index = elements[0].index;
const label = chart.data.labels[index];
const value = chart.data.datasets[0].data[index];
console.log("클릭: " + label + " = " + value);
}
},
onHover: (event, elements) => {
event.native.target.style.cursor =
elements.length > 0 ? 'pointer' : 'default';
},
}- •responsive: true — 컨테이너 크기에 따라 자동 리사이즈
- •plugins.legend — 범례의 위치, 스타일, 클릭 동작 설정
- •plugins.tooltip.callbacks — 툴팁 내용을 원하는 형식으로 커스터마이징
- •scales.y.ticks.callback — Y축 눈금 텍스트 포맷 지정
- •animation.easing — linear, easeInOut, easeOutBounce 등 다양한 이징 지원
💡
chart.update() 메서드를 호출하면 데이터나 옵션을 변경한 뒤 차트를 다시 그릴 수 있습니다. chart.data.datasets[0].data = newData; chart.update(); 패턴을 자주 사용합니다.