시작하기
설정과 첫 차트
Chart.js는 canvas 요소에 렌더링됩니다. type 속성이 차트 타입을 정합니다. data는 레이블과 값·스타일을 가진 datasets을 포함합니다.
<!-- include Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Green'],
datasets: [{
label: 'Votes',
data: [12, 19, 3],
backgroundColor: ['red', 'blue', 'green']
}]
}
});
</script>npm 설치와 ES 모듈 임포트
가장 간단한 설정에는 'chart.js/auto'를 사용하세요 — Chart.js와 모든 컨트롤러/엘리먼트를 임포트하고 자동 등록합니다. 더 작은 프로덕션 번들을 원하면 tree-shaking을 선호하세요: 'chart.js'에서 임포트하고 사용하는 조각만 등록합니다.
# install
npm install chart.js
// import the auto-bundled build (registers everything)
import Chart from 'chart.js/auto';
const ctx = document.getElementById('myChart');
const chart = new Chart(ctx, {
type: 'line',
data: { /* ... */ },
options: { responsive: true }
});Canvas와 2D 컨텍스트
Chart.js는 <canvas> 요소나 2d 렌더링 컨텍스트 중 하나를 받을 수 있습니다. responsive가 true이면 canvas가 컨테이너를 채우도록 크기 조정되므로, width/height HTML 속성은 폴백일 뿐입니다. 각 canvas에는 정확히 하나의 Chart 인스턴스만 담을 수 있습니다.
// Chart.js accepts a canvas element OR a 2D context
const canvas = document.getElementById('myChart');
const chart = new Chart(canvas, { type: 'bar', data: {...} });
// equivalent: pass the 2d context
const ctx = canvas.getContext('2d');
const chart2 = new Chart(ctx, { type: 'bar', data: {...} });
// one chart per canvas; the canvas size is controlled by
// responsive options, NOT the width/height attributes사용 가능한 차트 타입
Chart.js는 8가지 차트 타입을 제공합니다. Bar, line, scatter, bubble은 데카르트 축을 쓰고, pie, doughnut, polarArea는 원형이며, radar는 자체 방사형 축을 갖습니다. 최상위 'type' 필드가 모든 dataset에 사용될 컨트롤러를 선택하며, dataset이 자체 type으로 재정의하지 않는 한 그대로 적용됩니다.
// the 8 built-in chart types
const types = ['bar', 'line', 'pie', 'doughnut',
'radar', 'polarArea', 'bubble', 'scatter'];
// each type maps to a controller:
// bar/line -> Cartesian controllers
// pie/doughnut/polarArea -> circular controllers
// radar -> radar controller
// bubble/scatter -> cartesian with point parsing
new Chart(ctx, { type: 'polarArea', data: {...} });Tree-Shaking과 Register
'chart.js'(/auto 아님)에서 임포트하면 아무것도 등록되지 않으므로 컨트롤러, 엘리먼트, 스케일, 플러그인을 직접 등록해야 합니다. 이 tree-shakeable 방식은 번들 크기를 크게 줄일 수 있습니다. 컴포넌트 등록을 잊는 것이 가장 흔한 'scale is not a registered scale' 오류의 원인입니다.
import {
Chart,
BarController,
BarElement,
CategoryScale,
LinearScale,
Legend,
Title,
Tooltip,
} from 'chart.js';
// register ONLY what you use -> smaller bundle
Chart.register(
BarController, BarElement,
CategoryScale, LinearScale,
Legend, Title, Tooltip,
);
new Chart(ctx, {
type: 'bar',
data: { labels: ['A', 'B'], datasets: [{ data: [1, 2] }] },
});Destroy와 생명주기
각 Chart 인스턴스는 canvas와 연결된 이벤트 리스너를 소유합니다. destroy()를 호출하면 모두 해체되어 canvas를 재사용할 수 있습니다 — SPA와 React/Vue effect에서 필수입니다. 활성 canvas에 두 번째 차트를 만들면 메모리가 누출되고 그래픽이 이중으로 렌더링됩니다.
const chart = new Chart(ctx, config);
// ...later, to re-render with new config:
chart.destroy(); // cleans up listeners and canvas
const fresh = new Chart(ctx, newConfig);
// never create two Chart instances on the same canvas;
// always destroy() the old one first.막대 차트(Bar)
기본 막대 차트
막대 차트는 각 레이블을 데이터 값과 같은 높이의 막대에 매핑합니다. backgroundColor가 막대 채움을, borderColor/borderWidth가 외곽선을 정합니다. 막대가 항상 0에서 시작하도록 y.beginAtZero를 설정하세요 — 없으면 Chart.js가 축 최솟값을 자동 조정해 차이를 시각적으로 왜곡할 수 있습니다.
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'Revenue',
data: [12, 19, 7, 15, 22],
backgroundColor: 'rgba(54, 162, 235, 0.6)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: { scales: { y: { beginAtZero: true } } }
});가로 막대 (indexAxis)
Chart.js v3+에서 가로 막대는 'bar' 타입에 indexAxis: 'y'로 만듭니다 — 이전의 'horizontalBar' 타입은 제거되었습니다. x 스케일이 값 축이 됩니다. 가로 막대는 세로 차트에서 겹칠 긴 카테고리 레이블에 이상적입니다.
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Task A', 'Task B', 'Task C'],
datasets: [{ label: 'Hours', data: [5, 8, 3] }]
},
options: {
indexAxis: 'y', // horizontal bars (v3+ syntax)
scales: { x: { beginAtZero: true } }
}
});그룹 막대 (여러 dataset)
막대 차트의 여러 dataset은 기본적으로 나란히(그룹) 배치됩니다. backgroundColor를 생략해야 Chart.js가 색을 자동 배정하므로, 예측 가능한 출력을 위해 dataset마다 명시적 색을 설정하세요. 각 dataset은 x축에서 같은 labels 배열을 공유합니다.
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Q1', 'Q2', 'Q3', 'Q4'],
datasets: [
{ label: '2023', data: [20, 35, 30, 35],
backgroundColor: 'rgba(255,99,132,0.6)' },
{ label: '2024', data: [25, 32, 34, 40],
backgroundColor: 'rgba(54,162,235,0.6)' }
]
},
options: { scales: { y: { beginAtZero: true } } }
});누적 막대
누적 막대는 x와 y 스케일 둘 다에 stacked: true가 필요합니다. 각 dataset의 막대는 이전 막대 위에 그려져 합산됩니다. 누적은 구성 비율을 보여 주지만, 상위 시리즈는 그룹 막대보다 카테고리 간 비교가 어렵습니다.
new Chart(ctx, {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [
{ label: 'Men', data: [20, 35, 30], backgroundColor: '#36A2EB' },
{ label: 'Women', data: [25, 32, 34], backgroundColor: '#FF6384' }
]
},
options: {
scales: {
x: { stacked: true },
y: { stacked: true, beginAtZero: true }
}
}
});막대 스타일링
borderRadius는 막대 모서리를 둥글게 합니다(단일 숫자는 모든 모서리에 적용; {topLeft:8} 같은 객체는 특정 모서리만). borderSkipped는 기본적으로 'start'로 한 변을 생략합니다 — 네 변을 모두 그리려면 false로. barPercentage와 categoryPercentage가 함께 막대 두께와 간격을 조절합니다.
new Chart(ctx, {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
data: [10, 20, 15],
backgroundColor: '#FF6384',
borderColor: '#fff',
borderWidth: 2,
borderRadius: 8, // rounded corners (px or %)
borderSkipped: false, // draw border on all sides
barPercentage: 0.8, // bar width within category
categoryPercentage: 0.7 // category width
}]
}
});플로팅 막대 ([min, max])
데이터 값으로 [min, max] 쌍을 전달하면 0에서 시작하지 않는 플로팅 막대가 됩니다 — 일별 최저-최고 기온, 시가-종가, 신뢰 구간 같은 범위에 완벽합니다. 범위 막대에서는 y축이 0에서 시작하면 안 됩니다. 가로 막대에서도 동작합니다.
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Mon', 'Tue', 'Wed'],
datasets: [{
label: 'Low-High temp',
// each value is [min, max] -> a floating bar
data: [[10, 18], [12, 20], [8, 15]],
backgroundColor: 'rgba(75,192,192,0.6)'
}]
},
options: { scales: { y: { beginAtZero: false } } }
});선 차트(Line)
기본 선 차트
선 차트는 데이터 포인트를 순서대로 연결합니다. borderColor가 선 색이고, backgroundColor는 채움(fill 활성화 시)에 사용됩니다. tension(0~1)이 곡선의 부드러움을 조절합니다 — 0은 직선, 약 0.3~0.4가 완만한 베지어 곡선입니다. 금융 가격 같은 정밀 데이터에는 0을 사용하세요.
new Chart(ctx, {
type: 'line',
data: {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
datasets: [{
label: 'Visitors',
data: [30, 45, 28, 60, 52],
borderColor: 'rgba(75,192,192,1)',
backgroundColor: 'rgba(75,192,192,0.2)',
tension: 0.3
}]
},
options: { scales: { y: { beginAtZero: true } } }
});여러 선
선 차트의 각 dataset은 자기 선이 되며 기본 팔레트에서 색이 자동 배정됩니다(borderColor로 재정의 가능). 선은 dataset 순서대로 그려지므로 마지막 dataset이 위에 렌더링됩니다. 범례가 식별할 수 있도록 각 dataset에 label을 전달하세요.
new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr'],
datasets: [
{ label: 'Plan', data: [10, 20, 25, 30], borderColor: 'red' },
{ label: 'Actual', data: [8, 22, 24, 33], borderColor: 'blue' }
]
},
options: {
scales: { y: { beginAtZero: true } },
plugins: { legend: { position: 'top' } }
}
});선 Tension과 보간
tension은 베지어 스무딩을 더하지만 데이터 포인트를 넘어설 수 있습니다(최솟값 아래로 꺼짐). cubicInterpolationMode: 'monotone'은 넘어서지 않고 부드럽게 합니다 — 주가 같은 단조 데이터에 선호됩니다. borderDash는 파선/점선을 위한 [dash, gap] 패턴입니다.
datasets: [{
data: [1, 5, 2, 6, 3],
tension: 0, // straight lines
// tension: 0.4, // smooth bezier
cubicInterpolationMode: 'monotone', // no overshoot
borderDash: [5, 5], // dashed line
borderWidth: 2,
borderColor: 'purple'
}]채워진 선 (fill)
fill은 선 아래 영역을 제어합니다. true/'origin'은 x축까지 채웁니다. 숫자(1, -1, +1)는 인덱스로 다른 dataset 쪽을 채워 밴드 차트에 유용합니다. 음수는 이전 dataset 쪽으로 채웁니다. 채움을 통해 선이 보이도록 알파가 있는 backgroundColor를 설정하세요.
datasets: [
{ label: 'A', data: [3,5,4,6], fill: true, backgroundColor: 'rgba(255,99,132,0.3)' },
{ label: 'B', data: [1,2,3,2], fill: 'origin', backgroundColor: 'rgba(54,162,235,0.3)' },
{ label: 'C', data: [2,4,3,5], fill: 1, backgroundColor: 'rgba(75,192,192,0.3)' }
]
// fill values: false | true/'origin' | 1/-1/+1 | '-1' | {target:...}포인트 스타일링
포인트 속성은 단일 값이나 배열(포인트마다 하나)을 받습니다. pointStyle은 다양한 모양을 지원합니다('circle', 'rect', 'rectRot', 'triangle', 'star', 'cross', 'crossRot'). pointRadius: 0으로 포인트를 완전히 숨기고(촘촘한 선 차트에 유용), pointHoverRadius를 크게 하면 인터랙티브 팝 효과가 납니다.
datasets: [{
data: [4, 6, 5, 7],
showLine: true,
pointRadius: 5, // point size (0 hides points)
pointHoverRadius: 9,
pointBackgroundColor: 'white',
pointBorderColor: 'black',
pointBorderWidth: 2,
pointStyle: 'rectRot', // 'circle','rect','triangle','star','cross'...
// per-point arrays also work:
// pointRadius: [0, 0, 6, 0],
}]Span Gaps와 결측 데이터
null, undefined, NaN은 결측 데이터를 나타내며 기본적으로 선을 끊습니다. spanGaps: true는 끊긴 양쪽 포인트를 하나의 세그먼트로 연결합니다. NaN(결측)과 0(실제 영점)을 구분하세요 — 이를 혼동하는 것이 오해를 부르는 차트의 흔한 원인입니다.
datasets: [{
data: [5, null, 7, NaN, 9, undefined, 11],
spanGaps: true, // connect across null/NaN gaps
// spanGaps: false -> the line breaks at missing points
}]
// also skip points entirely by setting them to NaN
// NaN is "no data"; 0 is a legitimate zero value파이와 도넛 차트
기본 파이 차트
파이 차트는 전체 중 부분을 보여 줍니다: 각 값이 자기 비율에 비례하는 각도의 조각이 됩니다. 조각마다 backgroundColor를 하나씩(배열로) 제공하세요, 아니면 Chart.js가 기본 팔레트를 순환합니다. 파이 차트는 3~6개 카테고리에서 가장 잘 동작합니다 — 그 이상은 읽기 어렵습니다.
new Chart(ctx, {
type: 'pie',
data: {
labels: ['Rent', 'Food', 'Fun', 'Save'],
datasets: [{
data: [1200, 600, 400, 800],
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0']
}]
}
});기본 도넛 차트
도넛은 가운데에 구멍이 있는 파이입니다. cutout 속성(백분율 문자열이나 픽셀 수)이 구멍 크기를 조절합니다 — '50%'가 클래식한 도넛 모양입니다. 가운데 구멍은 플러그인으로 요약 레이블을 담을 수 있고, 링 길이는 조각 각도보다 값을 약간 더 잘 인코딩합니다.
new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
data: [40, 35, 25],
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56'],
cutout: '50%' // size of the inner hole
}]
}
});Cutout, 회전, Circumference
rotation이 시작 각도를 도 단위로 정합니다(기본 0 = 오른쪽; -90 = 위). circumference는 원의 어느 만큼을 그릴지 조절합니다 — 180은 반 도넛이며 게이지 스타일 차트에 유용합니다. 둘 다 v3+에서 options(가 아니라 dataset 아님)에 위치하지만, cutout은 어느 쪽에도 둘 수 있습니다.
new Chart(ctx, {
type: 'doughnut',
data: { labels: ['A','B','C'], datasets: [{ data: [30,40,30], backgroundColor: ['#f00','#0f0','#00f'] }] },
options: {
cutout: '60%',
rotation: -90, // start at top (degrees)
circumference: 360 // full circle; 180 = half doughnut
}
});테두리와 Offset
borderColor와 borderWidth가 조각을 시각적으로 분리합니다(흰 테두리가 깔끔한 분절 모양을 줍니다). hoverOffset은 사용자가 조각에 hover하면 밖으로 밀어 명확한 인터랙티브 피드백을 줍니다. offset은 배열(조각마다 하나)로 특정 조각을 영구적으로 '터져 보이게' 강조합니다.
datasets: [{
data: [30, 40, 30],
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56'],
borderColor: 'white',
borderWidth: 3,
hoverOffset: 16, // pop slice out on hover
offset: [0, 20, 0] // permanently offset 2nd slice
}]반 도넛 (게이지)
반 도넛(rotation: -90, circumference: 180)은 게이지/진행 계기처럼 읽힙니다. 센터 텍스트 플러그인과 짝지어 백분율을 표시하고, 깔끔한 KPI 모양을 위해 범례를 끄세요. 중립 회색의 '나머지' 조각이 미완료 부분을 전달합니다.
new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Done', 'Remaining'],
datasets: [{
data: [72, 28],
backgroundColor: ['#4BC0C0', '#E0E0E0']
}]
},
options: {
rotation: -90,
circumference: 180,
plugins: { legend: { display: false } }
}
});툴팁 백분율 콜백
파이/도넛 툴팁은 기본적으로 원시 값을 보여 줍니다. tooltip의 callbacks.label로 백분율을 계산해 표시하세요 — ctx.parsed가 조각 값이고 ctx.dataset.data가 합계에 쓸 모든 값을 담습니다. 이 치트시트의 코드 문자열에 포함된 콜백의 템플릿 리터럴은 백틱과 ${}를 이스케이프해야 합니다.
options: {
plugins: {
tooltip: {
callbacks: {
label: (ctx) => {
const total = ctx.dataset.data.reduce((a, b) => a + b, 0);
const pct = (ctx.parsed / total * 100).toFixed(1);
return `${ctx.label}: ${ctx.parsed} (${pct}%)`;
}
}
}
}
}레이더 차트
기본 레이더 차트
레이더 차트는 각 레이블을 다각형의 꼭짓점으로 놓고 닫힌 모양으로 연결합니다. fill: true는 내부를 음영 처리합니다. 방사형 스케일은 x/y가 아니라 scales.r 아래 설정합니다. 레이더는 다변량 프로필을 비교하지만 축이 너무 많거나 단위가 비교 불가하면 오해를 부를 수 있습니다.
new Chart(ctx, {
type: 'radar',
data: {
labels: ['Speed', 'Power', 'Range', 'Comfort', 'Price'],
datasets: [{
label: 'Model X',
data: [8, 7, 6, 9, 5],
borderColor: 'rgba(255,99,132,1)',
backgroundColor: 'rgba(255,99,132,0.2)',
fill: true
}]
},
options: { scales: { r: { beginAtZero: true } } }
});레이더 스타일링
레이더 dataset은 선 차트와 같은 스타일링을 받습니다: borderColor, fill, 포인트 스타일, tension. 작은 tension(0.1)은 꼭짓점을 약간 둥글게 해 부드러운 느낌을 주고, 0은 곧은 뾰족함을 유지합니다. 겹치는 레이더 모양이 보이도록 반투명 backgroundColor를 사용하세요.
datasets: [{
data: [7, 8, 6, 9, 5],
borderColor: 'blue',
backgroundColor: 'rgba(0,0,255,0.2)',
borderWidth: 2,
pointRadius: 4,
pointBackgroundColor: 'blue',
fill: true,
tension: 0.1 // slight curve between vertices
}]레이더 스케일 (r) 설정
방사형 스케일 r이 링과 레이블을 제어합니다. min/max가 모든 축에서 값 범위를 고정합니다(dataset 비교 시 필수). ticks.stepSize가 링 간격을 정하고, pointLabels가 둘레의 카테고리 이름을 스타일링합니다. 링 숫자가 그리드선을 가리지 않도록 ticks.backdropColor를 투명하게 하세요.
options: {
scales: {
r: {
min: 0,
max: 10,
ticks: { stepSize: 2, backdropColor: 'transparent' },
pointLabels: { font: { size: 13 }, color: '#333' },
grid: { color: '#ccc' },
angleLines: { color: '#ccc' }
}
}
}여러 dataset의 레이더
여러 dataset은 동심원 다각형으로 겹쳐지며, 전/후나 경쟁사 비교에 이상적입니다. 모양이 비교 가능하도록 항상 r에 같은 min/max를 설정하고, 겹치는 곳에서 두 프로필이 모두 보이도록 반투명 채움을 사용하세요.
new Chart(ctx, {
type: 'radar',
data: {
labels: ['A', 'B', 'C', 'D', 'E'],
datasets: [
{ label: 'Before', data: [5,6,4,7,5], borderColor: 'red', backgroundColor: 'rgba(255,0,0,0.15)', fill: true },
{ label: 'After', data: [7,8,6,9,7], borderColor: 'blue', backgroundColor: 'rgba(0,0,255,0.15)', fill: true }
]
}
});레이더 각도선과 그리드
angleLines는 중심에서 각 꼭짓점으로의 스포크이고, grid는 동심원 다각형 링입니다. ticks를 숨기면(display:false) 링은 유지하면서 숫자 링 레이블을 제거해 더 깔끔한 미학을 줍니다. pointLabels는 각 꼭짓점의 카테고리 텍스트만 제어합니다.
options: {
scales: {
r: {
angleLines: { display: true, color: 'rgba(0,0,0,0.2)', lineWidth: 1 },
grid: { display: true, color: 'rgba(0,0,0,0.1)' },
pointLabels: { display: true, color: '#000', font: { weight: 'bold' } },
ticks: { display: false } // hide numeric ring labels for a cleaner look
}
}
}폴라 에어리어 차트
기본 폴라 에어리어 차트
폴라 에어리어 차트는 각 값을 같은 각도(각각 360/N)를 덮는 부채꼴로 그리며, 반지름이 값을 인코딩합니다. 파이(각도 = 값)와 달리 여기서는 반지름 = 값이므로 모든 조각의 각 폭은 같고 길이만 다릅니다.
new Chart(ctx, {
type: 'polarArea',
data: {
labels: ['North', 'South', 'East', 'West'],
datasets: [{
data: [11, 16, 7, 14],
backgroundColor: ['#FF6384', '#4BC0C0', '#FFCE56', '#36A2EB']
}]
},
options: { scales: { r: { beginAtZero: true } } }
});폴라 에어리어 vs 파이
핵심 차이: 파이에서는 각 조각의 '각도'가 값에 비례하지만, 폴라 에어리어에서는 각 조각의 '반지름'이 값에 비례하고 각도는 같습니다. 모든 카테고리를 동등하게 보여 주되 크기로 구분하고 싶을 때 폴라 에어리어를 사용하세요.
// PIE: angle = value, radius = constant
new Chart(ctx, { type: 'pie', data: { datasets: [{ data: [10, 20, 30] }] } });
// POLAR: angle = constant, radius = value
new Chart(ctx, { type: 'polarArea', data: { datasets: [{ data: [10, 20, 30] }] } });
// polar area is better when values differ widely AND
// you want every category to occupy an equal angular share폴라 스케일 (r)
폴라 에어리어는 모든 부채꼴이 공유하는 단일 방사형 스케일 r을 사용합니다 — 모든 값이 같은 최대 반지름 기준으로 측정됩니다. 명시적 max를 설정하면 차트가 스케일에 대해 정직해 집니다; 없으면 Chart.js가 가장 큰 값으로 자동 스케일해 작은 차이를 과장할 수 있습니다.
options: {
scales: {
r: {
min: 0,
max: 20,
ticks: { stepSize: 5 },
grid: { color: 'rgba(0,0,0,0.15)' },
angleLines: { color: 'rgba(0,0,0,0.15)' }
}
}
}폴라 테두리 스타일링
폴라 에어리어 부채꼴은 파이/도넛과 같은 테두리/채움 스타일링을 받습니다. 흰 테두리가 인접한 부채꼴을 명확히 분리합니다. hoverBackgroundColor는 hover 시 부채꼴의 채움을 바꿔 인터랙티브 피드백을 줍니다. 도넛과 달리 cutout이 없습니다 — 부채꼴이 중심에서 만납니다.
datasets: [{
data: [11, 16, 7, 14],
backgroundColor: ['#FF6384', '#4BC0C0', '#FFCE56', '#36A2EB'],
borderColor: 'white',
borderWidth: 2,
hoverBackgroundColor: '#333'
}]Hover Offset을 가진 폴라
폴라 에어리어는 hoverBackgroundColor와 hoverBorderColor를 지원하지만 도넛처럼 hoverOffset / offset을 같은 방식으로 지원하지 않습니다. 부채꼴이 방사형 스케일을 공유하기 때문입니다. 조각을 '밀어내는' 것이 필수라면 도넛을 선택하세요. 폴라의 인터랙티비티는 색과 툴팁 변경으로 구현합니다.
datasets: [{
data: [11, 16, 7, 14],
backgroundColor: ['#FF6384', '#4BC0C0', '#FFCE56', '#36A2EB'],
hoverOffset: 12 // not supported on polarArea the same way as doughnut;
// use hoverBackgroundColor + tooltips for interactivity
}]
// for true "pop out" use 'doughnut' instead버블 차트
기본 버블 차트
버블 차트의 데이터 포인트는 {x, y, r} 객체이며 x, y는 좌표, r은 버블 '반지름'(픽셀)입니다. scatter와 달리 버블 크기가 세 번째 변수를 인코딩합니다. r은 반지 름(면적 아님)이므로 값이 2배면 면적은 시각적으로 4배입니다 — 크기 데이터를 sqrt 스케일링하는 것을 고려하세요.
new Chart(ctx, {
type: 'bubble',
data: {
datasets: [{
label: 'Products',
data: [
{ x: 10, y: 20, r: 15 },
{ x: 15, y: 10, r: 10 },
{ x: 7, y: 25, r: 8 }
],
backgroundColor: 'rgba(255,99,132,0.6)'
}]
},
options: { scales: { y: { beginAtZero: true } } }
});버블 크기 매핑
사람은 반지름보다 버블 '면적'을 지각하므로, r을 할당하기 전에 값을 Math.sqrt로 매핑하세요 — 값이 두 배면 보이는 면적도 두 배가 됩니다. 가장 큰 버블이 너무 많은 이웃과 겹치지 않게 하는 제수를 고르세요. 이렇게 하면 차트가 지각적으로 정직해 집니다.
const raw = [{x:1,y:2,pop:1000}, {x:2,y:3,pop:5000}, {x:3,y:1,pop:20000}];
// map a real-world value to a pixel radius with sqrt scaling
// so bubble AREA (not radius) is proportional to the value
const data = raw.map(d => ({
x: d.x,
y: d.y,
r: Math.sqrt(d.pop) / 10 // tune the divisor for your dataset
}));
new Chart(ctx, { type: 'bubble', data: { datasets: [{ data }] } });포인트별 버블 색상
다른 Chart.js dataset처럼 버블 스타일링 속성도 배열을 받아 버블마다 개별 스타일링이 가능합니다. 크기가 별도의 수치를 인코딩하는 동안 카테고리별로 버블에 색을 입히는 데 사용하세요 — 4차원 차트(x, y, 크기, 색)가 됩니다.
datasets: [{
data: [
{ x: 10, y: 20, r: 15 },
{ x: 15, y: 10, r: 10 }
],
// arrays give per-point styling
backgroundColor: ['rgba(255,99,132,0.6)', 'rgba(54,162,235,0.6)'],
borderColor: ['rgba(255,99,132,1)', 'rgba(54,162,235,1)'],
borderWidth: 2
}]여러 버블 dataset
여러 dataset은 다른 색의 버블 그룹으로 렌더링되며 각각 범례에 표시됩니다. 그룹을 겹칠 때는 버블 반지름을 절제하세요 — 버블이 서로를 완전히 가리지 않도록. 알파 투명 채움(0.5~0.6)이 겹치는 버블의 가독성을 유지해 줍니다.
new Chart(ctx, {
type: 'bubble',
data: {
datasets: [
{ label: 'Asia', data: [{x:1,y:2,r:10},{x:3,y:4,r:8}], backgroundColor: 'rgba(255,99,132,0.6)' },
{ label: 'Europe', data: [{x:2,y:5,r:12},{x:4,y:2,r:7}], backgroundColor: 'rgba(54,162,235,0.6)' }
]
}
});버블 Hover 스타일링
hover 속성(hoverBackgroundColor, hoverBorderColor, hoverBorderWidth, hoverRadius)은 포인터 아래 버블에만 적용됩니다. hoverRadius는 hover 시 반지름에 픽셀을 더해 대상 버블이 확실히 튀어 보이게 합니다. 툴팁과 결합하면 명확한 인터랙티브 포커스가 됩니다.
datasets: [{
data: [{x:1,y:2,r:10}],
backgroundColor: 'rgba(75,192,192,0.5)',
hoverBackgroundColor: 'rgba(75,192,192,0.9)',
hoverBorderColor: 'black',
hoverBorderWidth: 3,
hoverRadius: 2 // EXTRA radius added on hover (v3+ uses hoverRadius)
}]스캐터 차트
기본 스캐터 차트
스캐터 차트의 데이터 포인트는 {x, y} 객체입니다(반지름 불필요). x 스케일은 type: 'linear'(가 아님)여야 숫자 x 값이 실제 위치에 매핑됩니다. 스캐터는 두 연속 변수의 상관관계를 보여 주는 표준 차트입니다.
new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'Observations',
data: [
{ x: 1.2, y: 2.3 },
{ x: 1.8, y: 3.1 },
{ x: 2.5, y: 4.0 },
{ x: 3.1, y: 4.8 }
],
backgroundColor: 'rgba(75,192,192,0.7)'
}]
},
options: { scales: { x: { type: 'linear', position: 'bottom' } } }
});포인트가 많은 스캐터
수천 개의 포인트는 pointRadius를 줄이고(1~2px) 반투명 backgroundColor(알파 0.2~0.4)를 사용하세요 — 겹치는 포인트가 어두운 영역으로 밀도를 드러냅니다. 매우 큰 dataset에서는 인터랙션이 반응적이도록 포인트 hover를 비활성화하세요(pointHitRadius: 0).
const n = 2000;
const data = Array.from({ length: n }, () => ({
x: Math.random() * 100,
y: Math.random() * 100
}));
new Chart(ctx, {
type: 'scatter',
data: { datasets: [{ data, pointRadius: 1.5, backgroundColor: 'rgba(0,0,0,0.3)' }] }
});스캐터 포인트 스타일링
pointStyle은 기본 원 외에 다양한 모양을 지원합니다: 'rect', 'rectRot', 'triangle', 'star', 'cross', 'crossRot', 'dash'. pointRotation이 원형이 아닌 모양을 회전시킵니다. 모든 point* 속성은 포인트별 스타일링을 위한 배열을 받습니다 — 특정 관측치 강조에 유용합니다.
datasets: [{
data: [{x:1,y:2},{x:2,y:3}],
pointRadius: 8,
pointHoverRadius: 12,
pointStyle: 'triangle', // 'circle','rect','star','cross',...
pointBackgroundColor: 'red',
pointBorderColor: 'darkred',
pointBorderWidth: 2,
pointRotation: 45 // rotation in degrees (for shapes)
}]추세선이 있는 스캐터
Chart.js에는 내장 추세선이 없으므로 회귀(여기서는 최소제곱)를 계산하고 두 끝점과 pointRadius:0을 가진 'line' dataset을 추가하세요. line dataset의 type이 chart 단위 타입을 dataset별로 재정의합니다 — 혼합 차트가 동작하는 방식이기도 합니다. fill:false는 순수한 선으로 유지합니다.
// simple least-squares fit
const pts = [{x:1,y:2},{x:2,y:3.5},{x:3,y:4.2},{x:4,y:5.1}];
const n = pts.length;
const mX = pts.reduce((s,p)=>s+p.x,0)/n;
const mY = pts.reduce((s,p)=>s+p.y,0)/n;
const slope = pts.reduce((s,p)=>s+(p.x-mX)*(p.y-mY),0) / pts.reduce((s,p)=>s+(p.x-mX)**2,0);
const intercept = mY - slope*mX;
new Chart(ctx, {
type: 'scatter',
data: { datasets: [
{ data: pts, backgroundColor: 'blue' },
{ type: 'line', data: [{x:0,y:intercept},{x:5,y:slope*5+intercept}],
borderColor: 'red', pointRadius: 0, fill: false }
]}
});스캐터에서 선으로 (showLine)
스캐터 dataset에 showLine: true를 주면 포인트를 선으로 연결해 숫자 x 좌표를 쓰는 선 차트가 됩니다. x 값이 실수(카테고리 레이블이 아님)인데 연결 세그먼트가 필요할 때 올바른 선택입니다 — 예: 간격이 불규칙한 시계열.
new Chart(ctx, {
type: 'scatter',
data: { datasets: [{
data: [{x:1,y:2},{x:2,y:3},{x:3,y:5}],
showLine: true, // connect points with a line
borderColor: 'green',
backgroundColor: 'green',
pointRadius: 4
}]}
});데이터 — Datasets
Dataset 구조
data는 labels(모든 dataset이 공유)와 datasets(시리즈의 배열)을 담습니다. 각 dataset은 label(범례/툴팁에 표시), labels와 정렬된 data 배열, 스타일링 속성을 갖습니다. dataset에 설정된 속성은 배열로 재정의되지 않는 한 모든 포인트에 적용됩니다.
data: {
labels: ['A', 'B', 'C'], // shared category labels
datasets: [
{
label: 'Series 1', // legend + tooltip label
data: [10, 20, 30], // values (one per label)
backgroundColor: 'rgba(0,0,255,0.5)',
borderColor: 'blue',
borderWidth: 1,
// ... type-specific styling
}
]
}labels와 data 정렬
각 dataset의 data 배열은 공유 labels 배열과 위치로 정렬됩니다 — data[i]가 labels[i]의 값입니다. 더 짧은 data 배열은 누락된 꼬리에 undefined를 만들고, 선 차트는 이를 끊김으로 처리합니다. 의외의 끊김을 피하려면 labels와 data 길이를 항상 같게 유지하세요.
data: {
labels: ['Jan', 'Feb', 'Mar'],
datasets: [
{ data: [10, 20, 30] }, // Jan=10, Feb=20, Mar=30
{ data: [5, 15] } // Jan=5, Feb=15, Mar=undefined
]
}
// data[i] always corresponds to labels[i]; a shorter data array
// leaves the remaining positions as undefined (missing data)여러 dataset
여러 dataset은 병렬 시리즈로 렌더링됩니다(그룹 막대, 다중 선, 겹친 레이더). 하나의 labels 배열을 공유합니다. dataset마다 구별되는 색을 설정하세요 — Chart.js는 backgroundColor가 생략될 때만 자동으로 색을 입히며, 그때조차 명시적 색이 버전 간 더 예측 가능합니다.
data: {
labels: ['Q1','Q2','Q3','Q4'],
datasets: [
{ label: '2023', data: [20,35,30,35], backgroundColor: 'rgba(255,99,132,0.6)' },
{ label: '2024', data: [25,32,34,40], backgroundColor: 'rgba(54,162,235,0.6)' },
{ label: '2025', data: [28,38,36,45], backgroundColor: 'rgba(75,192,192,0.6)' }
]
}Dataset 수준 스타일링
dataset 수준 스타일은 그 dataset의 모든 포인트에 적용됩니다. hover* 변형은 hover 시 활성화됩니다. hidden:true로 시작하면 dataset이 숨겨진 상태로 시작합니다(범례 토글로 다시 볼 수 있음). order는 z-순서를 제어합니다 — 낮은 숫자가 나중에(위에) 그려짐 — 혼합/겹침 차트에 유용합니다.
datasets: [{
label: 'Revenue',
data: [10, 20, 30],
backgroundColor: 'rgba(54,162,235,0.6)',
borderColor: 'rgba(54,162,235,1)',
borderWidth: 2,
hoverBackgroundColor: 'rgba(54,162,235,0.9)',
hidden: false, // set true to hide from view + legend toggle
order: 0 // lower order draws on top
}]객체 데이터 파싱
데이터가 객체 배열일 때 parsing: {xAxisKey, yAxisKey}로 어느 필드가 축 값을 담는지 Chart.js에 알려 주세요. {x, y} 쌍으로 수동 매핑하는 것을 피합니다. 키는 기본 'x'와 'y'이므로 {x, y} 객체는 parsing 설정 없이 동작합니다.
new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
data: [
{ name: 'Red', votes: 12 },
{ name: 'Blue', votes: 19 }
],
parsing: { xAxisKey: 'name', yAxisKey: 'votes' }
}]
}
});포인트별 스타일링 배열
모든 스타일링 속성은 단일 값(모든 포인트에 적용)이거나 배열(포인트마다 하나)이 될 수 있습니다. 특정 포인트 강조를 가능하게 합니다 — 예: 대부분의 backgroundColor를 회색으로, 하나는 빨강으로 하여 주목을 끕니다. 배열 길이는 데이터 길이와 일치해야 하고; 짧은 배열은 순환합니다.
datasets: [{
data: [10, 20, 30, 40],
// every styling property accepts an array (one value per point)
backgroundColor: ['red', 'green', 'blue', 'orange'],
borderColor: ['darkred', 'darkgreen', 'darkblue', 'darkorange'],
borderWidth: [1, 2, 3, 4],
pointRadius: [3, 6, 9, 12] // (line/scatter only)
}]옵션 — 반응형과 스케일
옵션 구조
options는 최상위 설정 객체입니다. 관심사를 그룹화합니다: plugins(legend/title/tooltip), scales(x/y/r), layout(패딩), animation, interaction(hover 모드), events. 거의 모든 Chart.js 동작이 개별 dataset이 아니라 여기서 조정됩니다.
new Chart(ctx, {
type: 'bar',
data: { /* ... */ },
options: {
responsive: true,
maintainAspectRatio: true,
plugins: { legend: {}, title: {}, tooltip: {} },
scales: { x: {}, y: {} },
layout: { padding: 10 },
animation: { duration: 800 },
interaction: { mode: 'nearest', intersect: false },
events: ['mousemove', 'click', 'touchstart']
}
});Responsive와 maintainAspectRatio
responsive:true는 차트가 컨테이너 폭을 채우고 resize 시 다시 렌더링하게 합니다. maintainAspectRatio:false는 높이를 놓아 주어 컨테이너의 CSS 높이가 존중됩니다 — 둘 다 설정하고 canvas를 크기가 지정된 <div>로 감싸세요. maintainAspectRatio:true(기본)는 고정된 폭/높이 비율을 유지합니다.
<div style="width:100%; height:400px;">
<canvas id="c"></canvas>
</div>
<script>
new Chart(document.getElementById('c'), {
type: 'line',
data: { /* ... */ },
options: {
responsive: true, // resize with container
maintainAspectRatio: false // let the container control height
}
});
</script>스케일 개요
scales는 각 축을 설정합니다. id(x, y, r)가 스케일 키이고, type이 스케일 클래스를 선택합니다. 흔한 타입: 'category'(텍스트 레이블), 'linear'(숫자), 'logarithmic', 'time'(date 어댑터 필요), 'radialLinear'(레이더/폴라). title.display + text가 축 레이블을 추가합니다.
options: {
scales: {
x: { type: 'category', title: { display: true, text: 'Month' } },
y: { type: 'linear', title: { display: true, text: 'Value' },
beginAtZero: true },
r: { type: 'radialLinear' } // for radar/polarArea
}
}
// built-in scale types: category, linear, logarithmic, time,
// timeseries, radialLinear플러그인 개요
plugins는 내장 title, legend, tooltip 플러그인과 등록된 커스텀 플러그인의 옵션을 각자의 id로 묶습니다. title은 canvas 위에 차트 제목을 추가합니다. legend가 dataset 키를 제어합니다. tooltip이 hover 팝업을 제어합니다. 커스텀 플러그인도 같은 plugins 객체에서 옵션을 읽습니다.
options: {
plugins: {
title: { display: true, text: 'My Chart', font: { size: 18 } },
legend: { display: true, position: 'top' },
tooltip: { enabled: true, mode: 'index', intersect: false },
// a custom inline plugin:
myPlugin: { prop: 'value' }
}
}Layout (패딩)
layout.padding은 차트 영역과 canvas 가장자리 사이에 canvas 내부 공간을 추가합니다 — 제목, 축 레이블, 큰 툴팁이 잘리지 않게 하는 데 유용합니다. 단일 숫자는 모든 면에 균등하게 패딩을 주고, 객체 형태는 면별 값을 허용합니다.
options: {
layout: {
padding: {
top: 10, right: 20, bottom: 10, left: 20
}
}
}
// or a single number for all four sides:
// layout: { padding: 15 }전역 기본값 (Chart.defaults)
Chart.defaults는 전역 기본 설정을 담습니다 — 앱 시작 시 한 번 설정하면 모든 차트가 상속합니다. 브랜딩(폰트 패밀리, 기본 색, 기본 애니메이션)의 올바른 위치입니다. 차트별 옵션이 항상 기본값을 재정의하므로 개별 차트는 여전히 커스터마이즈할 수 있습니다.
// set once, applies to every chart created afterwards
Chart.defaults.font.family = "'Segoe UI', sans-serif";
Chart.defaults.font.size = 13;
Chart.defaults.color = '#333';
Chart.defaults.borderColor = '#ddd';
Chart.defaults.plugins.legend.labels.color = '#333';
Chart.defaults.animation.duration = 600;
// per-chart override still wins:
new Chart(ctx, { options: { font: { size: 16 } } });축 — X와 Y
선형 축
선형 축은 숫자를 비례적으로 매핑합니다. beginAtZero는 축이 0에서 시작하도록 강제합니다(막대 차트에 권장). min/max는 하드 한계이고; suggestedMin/suggestedMax는 Chart.js가 틱에 맞게 확장할 수 있는 소프트 힌트입니다. ticks.callback이 레이블 텍스트를 커스터마이즈합니다(예: 단위 추가).
options: {
scales: {
y: {
type: 'linear',
beginAtZero: true,
min: 0, max: 100, // hard limits
ticks: { stepSize: 10, callback: (v) => v + '%' }
}
}
}카테고리 축
카테고리 축은 고정 위치에 텍스트 레이블을 표시합니다. 막대/선 차트의 기본 x축입니다. ticks.autoSkip:false는 모든 레이블이 표시되도록 강제합니다(그렇지 않으면 Chart.js가 겹치는 것을 버립니다). maxRotation은 카테고리가 많을 때 겹침을 막으려고 레이블을 기울입니다.
options: {
scales: {
x: {
type: 'category',
labels: ['Mon','Tue','Wed'], // optional; usually from data.labels
ticks: { autoSkip: false, maxRotation: 45, minRotation: 0 }
}
}
}시간 축
시간 축은 Date 객체나 ISO 문자열을 시간에 비례하게 배치하며, 데이터가 없는 곳에는 빈틈이 생깁니다. date 어댑터 패키지(chartjs-adapter-date-fns, -luxon, -dayjs)가 필요합니다. time.unit이 틱 세분성을 고정합니다('day','month','year'); 없으면 Chart.js가 단위를 자동으로 고릅니다.