페블_
반짝이는 시냅스
페블_
전체 방문자
오늘
어제
  • 전체글 보기 (96)
    • QA (0)
    • 프로젝트 회고 (4)
    • 프로젝트 과정 기록 (12)
    • UI 구현 연구일지 (8)
    • Front-end (31)
      • Javascript (7)
      • CSS (10)
      • React (5)
      • Typescript (3)
      • Nextjs (3)
      • 스타일링 라이브러리 (3)
    • Back-end (0)
      • Express (0)
      • DB (0)
    • CS (0)
      • 자료구조 & 알고리즘 (0)
    • CI&CD (1)
    • 툴 사용법 (4)
      • Git (1)
      • Library&패키지 (2)
      • 기타 개발관련 (1)
    • 알고리즘 이론 & 풀이 (36)
      • 백준(BOJ) (14)
      • 프로그래머스 (22)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • emotion
  • storybook
  • Python
  • TypeScript
  • 알고리즘
  • 개발블로그_시작
  • 선형대수학
  • JS
  • 파이썬
  • chartjs
  • 토이프로젝트
  • UI 컴포넌트
  • react
  • 시리즈_표지
  • 백준
  • eslint
  • 생각
  • 캐러셀

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
페블_

반짝이는 시냅스

[JS] Chartjs 막대그래프 그리기 (별점 분포 차트)
프로젝트 과정 기록

[JS] Chartjs 막대그래프 그리기 (별점 분포 차트)

2023. 8. 3. 21:07

별점들을 표시하고 최빈값을 다른 색으로 표시하는 차트를 그릴 것이다.

 

1. 준비물

CDN 방식으로 라이브러리 불러오기

<script src="https://cdn.jsdelivr.net/npm/chart.js" defer></script>

 

script 부분

<script src="https://cdn.jsdelivr.net/npm/chart.js" defer></script>
<script src="index.js" defer></script>
<link href="style.css" rel="stylesheet" />

body 부분

<div class="chart-box">
  <canvas id="myChart"></canvas>
  <div id="average"></div>
</div>

 

2. 크키 지정 (반응형)

chartjs 옵션을 따로 설정할 필요 없이 차트 canvas를 div로 감싸고, 그 div에 max-width로 크기를 지정하면 된다.

.chart-box {
  margin: auto;
  max-width: 800px;
}

#average {
  margin-top: 30px;
  text-align: center;
}

 

3. 차트 그리기

const ratings = [
  { stars: 1, count: 100 },
  { stars: 2, count: 230 },
  { stars: 3, count: 700 },
  { stars: 4, count: 500 },
  { stars: 5, count: 520 },
];

const ctx = document.getElementById('myChart');

new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ratings.map((item) => `${item.stars}점`),
    datasets: [
      {
        label: '별점 분포',
        data: ratings.map((item) => item.count),
        borderWidth: 1,
      },
    ],
  },
  options: {
    scales: {
      x: {
        grid: {
          display: false, // bar 구분하는 격자 숨김
        },
      },
      y: {
        beginAtZero: true,
        grid: {
          display: false, // 눈금 격자 숨김
        },
        ticks: {	// tick이란 y축에서 100, 200 숫자 표시하는 부분. 보이지 않게 한다.
          display: false,
          callback: function (value, index, values) {
            return value.toLocaleString();
          },
        },
      },
    },
  },
});

 

4. 별점 평균 계산

const totalStars = ratings.reduce(
  (acc, curr) => acc + curr.stars * curr.count,
  0
);
const totalCount = ratings.reduce((acc, curr) => acc + curr.count, 0);
const average = (totalStars / totalCount).toFixed(1);
const averageElement = document.getElementById('average');
averageElement.innerHTML = `평균 ${average}점`;

 

여기까지 결과물

 

 

5. 막대 너비 조절 및 배경색 지정

최빈값에만 다른 색을 지정하기 위해 먼저 최빈값을 구한다.

const maxCount = Math.max(...ratings.map((item) => item.count));

 

data에 다음과 같이 backgroundColor, barPercentage, categoryPercentage 속성을 추가해준다.

  • barPercentage - 1로 설정하면 막대의 너비가 약간 넓어짐
  • categoryPercentage: 막대가 완전히 붙도록 더 커짐
data: {
    labels: ratings.map((item) => `${item.stars}점`),
    datasets: [
      {
        label: '별점 분포',
        data: ratings.map((item) => item.count),
        borderWidth: 1,
        backgroundColor: ratings.map((item) =>
          item.count === maxCount ? '#fcce03' : '#fcdb03'
        ),
        borderColor: '#fcba03',
        barPercentage: 1,
        categoryPercentage: 1,
      },
    ],
  },

backgroundColor에서 최빈값과 동일한 값에는 다른 색을 표시해준다.

borderColor는 주황색보다 약간 더 진한 주황색을 설정해 bar가 구별가게 해준다.

 

 

 

'프로젝트 과정 기록' 카테고리의 다른 글

[Project] Youtube Party 만들기 - 프로젝트 주제, 컨셉  (0) 2023.09.22
[React] Chartjs로 막대그래프 그리기  (0) 2023.08.04
[React] 회원가입 유효성 검사 구현하며 겪은 시행착오와 react-hook-form 사용  (0) 2023.07.31
[React] 카카오 지도 API - 키워드로 장소 검색하고 목록으로 보여주기 구현 +) Typescript  (0) 2023.07.17
[CSS] Navbar 아랫부분의 그림자가 가려지지 않게 하는 법 +) 가상클래스, react-router-dom Outlet, MUI  (0) 2023.07.13
    '프로젝트 과정 기록' 카테고리의 다른 글
    • [Project] Youtube Party 만들기 - 프로젝트 주제, 컨셉
    • [React] Chartjs로 막대그래프 그리기
    • [React] 회원가입 유효성 검사 구현하며 겪은 시행착오와 react-hook-form 사용
    • [React] 카카오 지도 API - 키워드로 장소 검색하고 목록으로 보여주기 구현 +) Typescript
    페블_
    페블_

    티스토리툴바