본문 바로가기
자바스크립트

Chart.js 사용하기

by 이시대최고개발자 2023. 5. 1.

chart.js

통계를 쉽게 chart로 확인할 수 있는 chart.js를 사용하는 방법을 알아보자

전체 소스는 맨 밑에!!

 


1. cdn 추가하기

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

jquery는 버전에 맞게 맞춰 사용하면 된다.

 


2. body에 div태그 넣기

<body>
  <div style="width: 1000px" style="height: 1000px"> <!--여기에 style 넣어서 사이즈 맞추기-->
    <!-- 크기를 지정하지 않으면 자동으로 부모의 사이즈에 맞추어 그려진다-->
    <canvas id="myChart"></canvas>
  </div>
</body>

 


3. 차트 생성하기

<script>
	const ctx = document.querySelector('#myChart');	// 선택자를 통해 body안에 그려줄 위치잡기
    
	// 화면이 처음 띄워질 때 나타나는 초기화 구문
    var myChart = new Chart(ctx, {
      type: 'doughnut',		// 차트에서 출력하고자하는 그래프의 형태
      data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        // labels는 차트의 항목이 된다
        datasets: [
          {
            label: '# 작년',
            data: [0, 0, 0, 0, 0, 0],	// label에 들어갈 값을 적는 부분
            borderWidth: 1,
          },
        ],
      },
      options: {
        scales: {
          y: {
            beginAtZero: true,
          },
        },
      },
    });
</script>

 


4. 버튼 만들기 

<body>
	<input class="button" type="button" value="월별" onclick="f_chart1()" />
	<input class="button" type="button" value="부위별" onclick="f_chart2()" />
	<input class="button" type="button" value="연령별" onclick="f_chart3()" />
</body>

비동기 방식으로 차트의 값을 바꾸기 위해 버튼 3개를 만들었다


5. 버튼을 클릭하면 함수를 실행하여 비동기 발생시키기

<script>
    function f_chart3() {	// 3번 버튼을 클릭하면 실행할 비동기함수
      $.ajax({
        method: 'get',	// 메소드는 나중에 서버로부터 값을 받아올 예정이니 get방식
        url: 'test2.csv',	// 현재 서버를 따로 만들지 않고 csv파일 형식으로 dummy데이터를 만들어 놨다
        dataType: 'text',	// dataType은 text형식을 받아준다
        success: function (res) {
          myChart.data.datasets[0].data = res.split(','); // split은 배열 리턴
          // 위에 생성해준 차트에 'test.csv'파일에서 가져온 값을 split함수를 통해
          // 배열로 바꿔주어 넣어준다
          
          myChart.data.labels = ['10대', '20대', '30대', '40대', '50대', '60대'];
          myChart.update(); // chart.js에서 제공하는 update()함수로 화면을 랜더링해준다
        },
        error: function (xhr, status, error) {
          // 요청이 실패하면 실행할 콜백 함수
        }
      });
    }
</script>

 

'test2.csv'파일은 단순히 dummy데이터로 파일 안에는 

20,30,10,5,22,30

모양의 데이터가 들어 있다.

 


6. 추가로 style css!

버튼 css를 추가해 보았다

<style>
  .button {
    display: inline-block;
    padding: 10px 20px;
    background-color: #2196f3;
    color: #fff;
    border-radius: 30px;
    border: none;
    box-shadow: 0px 8px 15px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease 0s;
    cursor: pointer;
  }

  .button:hover {
    background-color: #1976d2;
  }
</style>

 

 

 


7. 전체코드

<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Document</title>
</head>
<style>
  .button {
    display: inline-block;
    padding: 10px 20px;
    background-color: #2196f3;
    color: #fff;
    border-radius: 30px;
    border: none;
    box-shadow: 0px 8px 15px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease 0s;
    cursor: pointer;
  }

  .button:hover {
    background-color: #1976d2;
  }
</style>

<body>
  <div style="width: 1000px" style="height: 1000px">
    <canvas id="myChart"></canvas>
  </div>

  <input class="button" type="button" value="월별" onclick="f_chart1()" />
  <input class="button" type="button" value="부위별" onclick="f_chart2()" />
  <input class="button" type="button" value="연령별" onclick="f_chart3()" />

  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


  <script>

    function f_chart1() {
      $.ajax({
        method: 'get',
        url: 'salesRevenue.csv',
        dataType: 'text',
        success: function (res) {
          myChart.data.datasets[0].data = res.split(',');
          myChart.data.labels = ['1월', '2월', '3월', '4월', '5월', '6월'];
          myChart.update();
        },
        error: function (xhr, status, error) {

        }
      });
    }
    function f_chart2() {
      $.ajax({
        method: 'get',
        url: 'test.csv',
        dataType: 'text',
        success: function (res) {
          myChart.data.datasets[0].data = res.split(',');
          myChart.data.labels = ['팔', '다리', '손가락', '발목', '어깨', '허리'];
          myChart.update();
        },
        error: function (xhr, status, error) {

        }
      });
    }
    function f_chart3() {
      $.ajax({
        method: 'get',
        url: 'test2.csv',
        dataType: 'text',
        success: function (res) {
          myChart.data.datasets[0].data = res.split(',');
          myChart.data.labels = ['10대', '20대', '30대', '40대', '50대', '60대'];
          myChart.update();
        },
        error: function (xhr, status, error) {

        }
      });
    }

    const ctx = document.querySelector('#myChart');

    var myChart = new Chart(ctx, {
      type: 'doughnut',
      data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [
          {
            label: '# 작년',
            data: [0, 0, 0, 0, 0, 0],
            borderWidth: 1,
          },
        ],
      },
      options: {
        scales: {
          y: {
            beginAtZero: true,
          },
        },
      },
    });
  </script>
</body>

</html>

'자바스크립트' 카테고리의 다른 글

$.each  (0) 2023.05.23
ajax를 만들어서 사용해보자  (0) 2023.04.28
sweetalert 쉽게 사용하기  (0) 2023.04.28

댓글