차트 (Chart.js)
CI4 JSON API와 Chart.js를 연동하는 다양한 차트 패턴을 보여줍니다.
게시글 조회수 순위 (Line)
게시글을 조회수 내림차순으로 정렬해 각 게시글의 조회수 분포를 꺾은선으로 표시합니다.
작성자별 게시글 수 & 평균 조회수 (Bar)
작성자별 게시글 수(파란색)와 평균 조회수(빨간색)를 나란히 비교합니다.
조회수 구간별 분포 (Doughnut)
게시글 조회수를 구간(1~100, 101~200, 201~300, 301~)으로 나눠 분포를 표시합니다.
작성자별 게시글 수(Bar) + 총 조회수(Line) (Mixed)
작성자별 게시글 수(막대)와 총 조회수(꺾은선)를 이중 Y축으로 한 차트에 표시합니다.
1
CI4 Controller — JSON 데이터 반환
// 월별 게시글 수 집계
public function lineData(): ResponseInterface
{
$rows = db_connect()
->table('posts')
->select("strftime('%Y-%m', created_at) as month, COUNT(*) as count")
->where('deleted_at', null)
->groupBy('month')
->orderBy('month', 'ASC')
->get()->getResultArray();
return $this->response->setJSON([
'labels' => array_column($rows, 'month'),
'data' => array_map('intval', array_column($rows, 'count')),
]);
}
2
Chart.js — fetch API로 데이터 로드
const res = await fetch('/examples/chart/line-data');
const json = await res.json();
new Chart(document.getElementById('lineChart'), {
type: 'line',
data: {
labels: json.labels,
datasets: [{
label: '게시글 수',
data: json.data,
fill: true,
tension: 0.4, // 곡선 스무딩
}]
},
options: {
responsive: true,
plugins: { legend: { position: 'top' } },
}
});
3
복합 차트 — type 혼용
new Chart(ctx, {
data: {
labels: json.labels,
datasets: [
{
type: 'bar', // 막대
label: '게시글 수',
data: json.counts,
yAxisID: 'y',
},
{
type: 'line', // 꺾은선 (같은 차트에 중첩)
label: '평균 조회수',
data: json.avgViews,
yAxisID: 'y1', // 별도 Y축
tension: 0.4,
}
]
},
options: {
scales: {
y: { position: 'left' },
y1: { position: 'right', grid: { drawOnChartArea: false } }
}
}
});
4
Chart.js CDN
<!-- jsDelivr CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
버전을 고정하려면 chart.js@4.4.4 처럼 명시합니다.