본문 바로가기
개발/Javascript

[Javascript] Chart.js bar chart 만들기

by devhooney 2022. 8. 16.
728x90

- 지난번에 radar 차트를 만들었었다.

- 차트 종류가 매우 많은데, 하나씩 만들어보려 한다.

 

- 그 중에 이번엔 bar 차트를 만들어본다.

 

<th:block layout:fragment="script">
	<script type ="text/javascript" 
    th:src="@{https://cdn.jsdelivr.net/npm/chart.js@3.8.2/dist/chart.min.js}"></script>
</th:block>

<canvas id="chart" width="400" height="400"></canvas>

- 나는 thymeleaf를 사용 중이기 때문에 th:src="@{~~}" 이런 문법이 들어가 있지만, 보통은 src="~~" 이렇게 코드를 넣어주면 된다. 

- th:block도 필요 없다.

 

- 라벨은 x축 눈금에 표시될 문자를 말한다.

- 데이터는 10년 동안 이탈리아 프로 축구 리그 Seria A의 우승팀과 횟수이다.

const ctx = document.getElementById('chart').getContext('2d');
const chart = new Chart(ctx, {
  type: 'bar',  
  data: {
    labels: ['AC Milan','Inter','Juventus'],
    datasets: [
      {
          label: '우승 횟수',
          backgroundColor: '#009900',
          borderColor: '#ffffff',
          borderRadius: 50,
          data: [1 ,1, 8]
      },
    ]
  },
});

- 이런 차트가 만들어진다.

 

- 역대 우승 횟수 막대를 추가하면?

const ctx = document.getElementById('chart').getContext('2d');
const chart = new Chart(ctx, {
  type: 'bar',  
  data: {
    labels: ['AC Milan','Inter','Juventus'],
    datasets: [
      {
          label: '우승 횟수',
          backgroundColor: '#009900',
          borderColor: '#ffffff',
          borderRadius: 50,
          data: [1 ,1, 8]
      },
      {
          label: '역대 우승 횟수',
          backgroundColor: 'red',
          borderColor: '#ffffff',
          borderRadius: 50,
          data: [19 ,19, 36]
      },
    ]
  },
});

 

- 챔피언스 리그 횟수 까지 더해주자

const ctx = document.getElementById('chart').getContext('2d');
const chart = new Chart(ctx, {
  type: 'bar',  
  data: {
    labels: ['AC Milan','Inter','Juventus'],
    datasets: [
      {
          label: '우승 횟수',
          backgroundColor: '#009900',
          borderColor: '#ffffff',
          borderRadius: 50,
          data: [1 ,1, 8]
      },
      {
          label: '챔피언스리그 우승 횟수',
          backgroundColor: '#fff',
          borderColor: '#d3d3d3',
          borderRadius: 50,
          borderWidth: 2,
          data: [7 ,2, 2]
      },
      {
          label: '역대 우승 횟수',
          backgroundColor: 'red',
          borderColor: '#ffffff',
          borderRadius: 50,
          data: [19 ,19, 36]
      },
    ]
  },
});

- 이렇게 막대 그래프를 그려봤다.

 

- type 아래에

options: { indexAxis: 'y'},

를 추가할 경우 가로형 막대로 바뀐다.

 

 

chartjs는 기본형 차트 그리는게 정말 간단하다.

728x90