chart.js를 이용하여 차트 그리는 방법을 정리했다.
시나리오
1. 사용자가 처음 페이지를 호출하면 빈 차트를 보여준다.
2. ajax로 json 형태의 데이터를 요청/수신하고, 차트만 다시 그린다.
사용자가 처음 페이지를 호출하면 빈 차트를 보여준다.
빈 차트를 생성해서 canvas에 그려준다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<script> $(document).ready(function() { // 빈 차트를 생성한다. var chart = new Chart(document.getElementById("myChart"), { type: 'line', data: { labels: [], datasets: [ {label: [], data: [],}, {label: [], data: [],} ], borderWidth: 1 }, }); <!-- ajax를 이용하여 json 타입의 데이터를 수신 --> <!-- 코드 생략 --> }); </script> <!-- 차트 그릴 영역 --> <canvas id="myChart"></canvas> <button type="button" id="search">조회</button>코 |
코드를 실행하면 아래와 같은 형태의 차트가 생성된다.
ajax로 json 형태의 데이터를 요청/수신하고, 차트만 다시 그린다.
ajax를 이용하여 json 형태로 데이터를 받는다.
[{“label”:[“202101″,”202102″,”202103″,”202104″,”202105″,”202106″,”202107”],
“height”:[26000,26000,26000,26000,26000,26500,26500],
“weight”:[33500,33500,33500,33500,33500,34000,34000]}]
위의 데이터를 이용하여 canvas에 차트를 새로 그린다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
$("#search").on('click', function() {
$.ajax({
url: URL,
type: 'get',
dataType: 'json',
success: function (data) {
chart.destroy(); // 기존에 생성한 차트 오브젝트를 없앤다.
// 수신한 json 타입 데이터를 이용하여 차트를 새로 그린다.
chart = new Chart(document.getElementById("myChart"), {
type: 'line',
data: {
labels: data[0].label,
datasets: [
{
label: "height",
data: data[0].height,
borderColor: 'rgba(255, 0, 0, 1)',
},
{
label: "weight",
data: data[0].weight,
borderColor: 'rgba(0, 50, 255, 1)',
}
],
borderWidth: 1
},
});
},
error: function (xhr, status, error) {
// 블라블라
},
complete: function (data) {
// 블라블라
}
})
});
|
아래와 같은 형태의 차트가 생성된다.


